[フレーム]
WordPress.org
Get WordPress
WordPress.org

WordPress Developer Resources

wp_enqueue_script()

Home Reference Functions wp_enqueue_script()

wp_enqueue_script( string $handle, string $src = '', string[] $deps = array(), string|bool|null $ver = false, array|bool $args = array() )

Enqueues a script.

Description

Registers the script if $src provided (does NOT overwrite), and enqueues it.

See also

Parameters

$handlestringrequired
Name of the script. Should be unique.
$srcstringoptional
Full URL of the script, or path of the script relative to the WordPress root directory.

Default:''

$depsstring[]optional
An array of registered script handles this script depends on.

Default:array()

$verstring|bool|nulloptional
String specifying script version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version.
If set to null, no version is added.

Default:false

$argsarray|booloptional
An array of additional script loading strategies.
Otherwise, it may be a boolean in which case it determines whether the script is printed in the footer. Default false.
  • strategy string
    Optional. If provided, may be either 'defer' or 'async'.
  • in_footer bool
    Optional. Whether to print the script in the footer. Default 'false'.

Default:array()

More Information

Usage

wp_enqueue_script( $handle, $src, $deps, $ver, $args );

Links a script file to the generated page at the right time according to the script dependencies, if the script has not been already included and if all the dependencies have been registered. You could either link a script with a handle previously registered using the wp_register_script() function, or provide this function with all the parameters necessary to link a script.

This is the recommended method of linking JavaScript to a WordPress generated page.

As of WordPress 6.3, the new $args parameter – that replaces/overloads the prior $in_footer parameter – can be used to specify a script loading strategy. See the sections to follow for more information.

Supported strategies are as follows:

  • defer
    • Added by specifying an array key value pair of 'strategy' => 'defer' to the $args parameter.
    • Scripts marked for deferred execution — via the defer script attribute — are only executed once the DOM tree has fully loaded (but before the DOMContentLoaded and window load events). Deferred scripts are executed in the same order they were printed/added in the DOM, unlike asynchronous scripts.
  • async
    • Added by specifying an array key value pair of 'strategy' => 'async' to the $args parameter.
    • Scripts marked for asynchronous execution — via the async script attribute — are executed as soon as they are loaded by the browser. Asynchronous scripts do not have a guaranteed execution order, as script B (although added to the DOM after script A) may execute first given that it may complete loading prior to script A. Such scripts may execute either before the DOM has been fully constructed or after the DOMContentLoaded event.

Following is an example of specifying a loading strategy during script enqueuing:

wp_enqueue_script(
'foo',
'/path/to/foo.js',
array(),
'1.0.0',
array(
'strategy' => 'defer',
)
);

The same approach applies when using

wp_register_script()

.

When applying a loading strategy via either the wp_register_script() and wp_enqueue_script() functions, the scripts dependency tree is taken into consideration and the most eligible loading strategy is applied.

While the intended (delayed) strategy passed by the code author may not be the final one, it will never be a stricter one, thus maintaining the integrity of the dependency tree.

Notes

  • The function should be called using the wp_enqueue_scripts action hook if you want to call it on the front-end of the site, like in the examples above. To call it on the administration screens, use the admin_enqueue_scripts action hook. For the login screen, use the login_enqueue_scripts action hook. Calling it outside of an action hook can lead to problems, see the ticket #11526 for details.
  • If you try to register or enqueue an already registered handle with different parameters, the new parameters will be ignored. Instead, use wp_deregister_script() and register the script again with the new parameters.
  • jQuery UI Effects is not included with the jquery-ui-core handle.
  • This function relies on the use of wp_head() and wp_footer() by the active theme. This means that it may not work with a few very old themes that do not call these functions. This is useful to keep in mind when debugging ancient themes.
  • Uses: WP_Scripts::add(), WP_Scripts::add_data() and WP_Scripts::enqueue().
  • Uses global: (unknown type) $wp_scripts.

Default Scripts and JS Libraries Included and Registered by WordPress

By default, WordPress installation includes many popular javascript libraries and scripts commonly used by web developers besides the scripts used by WordPress itself. Some of them are listed in the table below.

For a detailed list of names that can be used in place of the $handle parameter, see wp_register_script().

Script Name
Handle
Needed Dependency *
Script version
License
Image Cropper Image cropper (not used in core, see jcrop)
Jcrop jcrop0.9.12MIT
SWFObject swfobject2.2-20120417MIT
SWFUpload swfupload2201-20110113MIT
SWFUpload Degrade swfupload-degrade2201MIT
SWFUpload Queue swfupload-queue2201MIT
SWFUpload Handlers swfupload-handlers2201-20110524MIT
jQuery jqueryjson2 (for AJAX calls)3.6.0MIT + (MIT OR BSD)
jQuery Form jquery-formjquery4.3.0MIT OR LGPLv3
jQuery Color jquery-colorjquery2.2.0MIT+CC0 + (MIT OR GPLv2)
jQuery Masonry jquery-masonryjquery3.1.2bMIT
Masonry (native Javascript) masonryimagesloaded4.2.2MIT
jQuery UI Core jquery-ui-corejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Widget Now part of `jquery-ui-core`jquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Accordion jquery-ui-accordionjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Autocomplete jquery-ui-autocompletejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Button jquery-ui-buttonjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Datepicker jquery-ui-datepickerjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Dialog jquery-ui-dialogjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Draggable jquery-ui-draggablejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Droppable jquery-ui-droppablejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Menu jquery-ui-menujquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Mouse jquery-ui-mousejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Position Now part of `jquery-ui-core`jquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Progressbar jquery-ui-progressbarjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Selectable jquery-ui-selectablejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Resizable jquery-ui-resizablejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Selectmenu jquery-ui-selectmenujquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Sortable jquery-ui-sortablejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Slider jquery-ui-sliderjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Spinner jquery-ui-spinnerjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Tooltips jquery-ui-tooltipjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Tabs jquery-ui-tabsjquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects jquery-effects-corejquery1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Blind jquery-effects-blindjquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Bounce jquery-effects-bouncejquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Clip jquery-effects-clipjquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Drop jquery-effects-dropjquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Explode jquery-effects-explodejquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Fade jquery-effects-fadejquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Fold jquery-effects-foldjquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Highlight jquery-effects-highlightjquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Pulsate jquery-effects-pulsatejquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Scale jquery-effects-scalejquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Shake jquery-effects-shakejquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Slide jquery-effects-slidejquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
jQuery UI Effects – Transfer jquery-effects-transferjquery-effects-core1.13.1MIT + CC0 + (MIT OR GPLv2)
MediaElement.js (WP 3.6+) wp-mediaelementjquery4.2.16MIT
jQuery Schedule schedulejquery20m/1.0.1MIT
jQuery Suggest suggestjquery1.1-20110113Public domain
ThickBox thickbox3.1-20121105MIT OR GPLv3
jQuery HoverIntent hoverIntentjquery1.10.1MIT
jQuery Hotkeys jquery-hotkeysjquery0.2.0MIT OR GPLv2
Simple AJAX Code-Kit sack1.6.1X11 License
QuickTags quicktags1.3LGPL2.1
Iris (Colour picker) irisjquery1.1.1GPLv2
Farbtastic (deprecated) farbtasticjquery1.2GPLv3
ColorPicker (deprecated) colorpickerjqueryv2Author’s own copyright
Tiny MCE wp-tinymce4.9.4LGPL2.1
Autosaveautosave
WordPress AJAX Responsewp-ajax-response
List Manipulationwp-lists
WP Commoncommon
WP Editoreditorremov
WP Editor Functionseditor-functions
AJAX Catajaxcat
Admin Categoriesadmin-categories
Admin Tagsadmin-tags
Admin custom fieldsadmin-custom-fields
Password Strength Meterpassword-strength-meter
Admin Commentsadmin-comments
Admin Usersadmin-users
Admin Formsadmin-forms
XFNxfn
Uploadupload
PostBoxpostbox
Slugslug
Postpost
Pagepage
Linklink
Commentcomment
Threaded Commentscomment-reply
Admin Galleryadmin-gallery
Media Uploadmedia-upload
Admin widgetsadmin-widgets
Word Countword-count
Theme Previewtheme-preview
JSON for JS json22015年05月03日Public domain
Plupload Core plupload2.1.9GPLv2
Plupload All Runtimes plupload-all2.1.1GPLv2
Plupload HTML4 plupload-html42.1.1GPLv2
Plupload HTML5 plupload-html52.1.1GPLv2
Plupload Flash plupload-flash2.1.1GPLv2
Plupload Silverlight plupload-silverlight2.1.1GPLv2
Underscore js underscore1.13.1MIT
Backbone js backbonejquery, underscore1.4.0MIT
imagesLoaded imagesloaded4.1.4MIT
CodeMirror wp-codemirror5.29.1-alpha-ee20357MIT
imgAreaSelect imgareaselectjquery0.9.8MIT AND GPL
Removed from Core
Script NameHandleRemoved VersionReplaced With
Scriptaculous Root scriptaculous-rootWP 3.5Google Version
Scriptaculous Builder scriptaculous-builderWP 3.5Google Version
Scriptaculous Drag & Drop scriptaculous-dragdropWP 3.5Google Version
Scriptaculous Effects scriptaculous-effectsWP 3.5Google Version
Scriptaculous Slider scriptaculous-sliderWP 3.5Google Version
Scriptaculous Soundscriptaculous-soundWP 3.5Google Version
Scriptaculous Controls scriptaculous-controlsWP 3.5Google Version
Scriptaculous scriptaculousWP 3.5Google Version
Prototype Framework prototypeWP 3.5Google Version

The list is far from complete. For a complete list of registered files inspect $GLOBALS['wp_scripts'] in the admin UI. Registered scripts might change per requested page.


* The listed dependencies are not complete.

Source

function wp_enqueue_script( $handle, $src = '', $deps = array(), $ver = false, $args = array() ) {
	_wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
	$wp_scripts = wp_scripts();
	if ( $src || ! empty( $args ) ) {
		$_handle = explode( '?', $handle );
		if ( ! is_array( $args ) ) {
			$args = array(
				'in_footer' => (bool) $args,
			);
		}
		if ( $src ) {
			$wp_scripts->add( $_handle[0], $src, $deps, $ver );
		}
		if ( ! empty( $args['in_footer'] ) ) {
			$wp_scripts->add_data( $_handle[0], 'group', 1 );
		}
		if ( ! empty( $args['strategy'] ) ) {
			$wp_scripts->add_data( $_handle[0], 'strategy', $args['strategy'] );
		}
	}
	$wp_scripts->enqueue( $handle );
}

View all references View on Trac View on GitHub

UsesDescription
WP_Scripts::add_data() wp-includes/class-wp-scripts.php

This overrides the add_data method from WP_Dependencies, to support normalizing of $args.

wp_scripts() wp-includes/functions.wp-scripts.php

Initializes $wp_scripts if it has not been set.

Used byDescription
wp_enqueue_block_template_skip_link() wp-includes/theme-templates.php

Enqueues the skip-link script & styles.

_wp_get_iframed_editor_assets() wp-includes/block-editor.php

Collect the block editor assets that need to be loaded into the editor’s iframe.

wp_maybe_enqueue_oembed_host_js() wp-includes/embed.php

Enqueue the wp-embed script if the provided oEmbed HTML contains a post embed.

wp_enqueue_editor_format_library_assets() wp-includes/script-loader.php

Enqueues the assets required for the format library within the block editor.

WP_Block::render() wp-includes/class-wp-block.php

Generates the render output for the block.

wp_enqueue_editor_block_directory_assets() wp-includes/script-loader.php

Enqueues the assets required for the block directory within the block editor.

enqueue_editor_block_styles_assets() wp-includes/script-loader.php

Function responsible for enqueuing the assets required for block styles functionality on the editor.

wp_enqueue_registered_block_scripts_and_styles() wp-includes/script-loader.php

Enqueues registered block scripts and styles, depending on current rendered context (only enqueuing editor scripts while in context of the editor).

the_block_editor_meta_boxes() wp-admin/includes/post.php

Renders the meta boxes forms.

register_and_do_post_meta_boxes() wp-admin/includes/meta-boxes.php

Registers the default post meta boxes, and runs the do_meta_boxes actions.

WP_Privacy_Policy_Content::notice() wp-admin/includes/class-wp-privacy-policy-content.php

Adds a notice with a link to the guide when editing the privacy policy page.

wp_enqueue_code_editor() wp-includes/general-template.php

Enqueues assets needed by the code editor for the given settings.

WP_Widget_Media_Gallery::enqueue_admin_scripts() wp-includes/widgets/class-wp-widget-media-gallery.php

Loads the required media files for the media manager and scripts for media widgets.

WP_Widget_Custom_HTML::enqueue_admin_scripts() wp-includes/widgets/class-wp-widget-custom-html.php

Loads the required scripts and styles for the widget control.

WP_Widget_Text::enqueue_admin_scripts() wp-includes/widgets/class-wp-widget-text.php

Loads the required scripts and styles for the widget control.

WP_Widget_Media_Audio::enqueue_admin_scripts() wp-includes/widgets/class-wp-widget-media-audio.php

Loads the required media files for the media manager and scripts for media widgets.

WP_Widget_Media_Video::enqueue_preview_scripts() wp-includes/widgets/class-wp-widget-media-video.php

Enqueue preview scripts.

WP_Widget_Media_Video::enqueue_admin_scripts() wp-includes/widgets/class-wp-widget-media-video.php

Loads the required scripts and styles for the widget control.

WP_Widget_Media_Audio::enqueue_preview_scripts() wp-includes/widgets/class-wp-widget-media-audio.php

Enqueue preview scripts.

WP_Widget_Media::enqueue_admin_scripts() wp-includes/widgets/class-wp-widget-media.php

Loads the required scripts and styles for the widget control.

WP_Widget_Media_Image::enqueue_admin_scripts() wp-includes/widgets/class-wp-widget-media-image.php

Loads the required media files for the media manager and scripts for media widgets.

the_custom_header_markup() wp-includes/theme.php

Prints the markup for a custom header.

WP_Customize_Selective_Refresh::enqueue_preview_scripts() wp-includes/customize/class-wp-customize-selective-refresh.php

Enqueues preview scripts.

WP_Customize_Cropped_Image_Control::enqueue() wp-includes/customize/class-wp-customize-cropped-image-control.php

Enqueue control related scripts/styles.

WP_Customize_Nav_Menus::customize_preview_enqueue_deps() wp-includes/class-wp-customize-nav-menus.php

Enqueues scripts for the Customizer preview.

WP_Customize_Nav_Menus::enqueue_scripts() wp-includes/class-wp-customize-nav-menus.php

Enqueues scripts and styles for Customizer pane.

wp_dashboard_setup() wp-admin/includes/dashboard.php

Registers dashboard widgets.

WP_Internal_Pointers::enqueue_scripts() wp-admin/includes/class-wp-internal-pointers.php

Initializes the new feature pointers.

do_accordion_sections() wp-admin/includes/template.php

Meta Box Accordion Template Function.

wp_media_upload_handler() wp-admin/includes/media.php

Handles the process of uploading media.

media_upload_gallery() wp-admin/includes/media.php

Retrieves the legacy media uploader form in an iframe.

enqueue_comment_hotkeys_js() wp-admin/includes/comment.php

Enqueues comment shortcuts jQuery script.

Custom_Image_Header::js_includes() wp-admin/includes/class-custom-image-header.php

Sets up the enqueue for the JavaScript files.

Custom_Background::admin_load() wp-admin/includes/class-custom-background.php

Sets up the enqueue for the CSS & JavaScript files.

WP_Customize_Manager::enqueue_control_scripts() wp-includes/class-wp-customize-manager.php

Enqueues scripts for customize controls.

WP_Customize_Manager::customize_preview_init() wp-includes/class-wp-customize-manager.php

Prints JavaScript settings.

add_thickbox() wp-includes/general-template.php

Enqueues the default ThickBox js and css.

wp_auth_check_load() wp-includes/functions.php

Loads the auth check for monitoring whether the user is still logged in.

WP_Admin_Bar::initialize() wp-includes/class-wp-admin-bar.php

Initializes the admin bar.

WP_Customize_Header_Image_Control::enqueue() wp-includes/customize/class-wp-customize-header-image-control.php
WP_Customize_Color_Control::enqueue() wp-includes/customize/class-wp-customize-color-control.php

Enqueue scripts/styles for the color picker.

WP_Customize_Widgets::enqueue_scripts() wp-includes/class-wp-customize-widgets.php

Enqueues scripts and styles for Customizer panel and export data to JavaScript.

WP_Customize_Widgets::customize_preview_enqueue() wp-includes/class-wp-customize-widgets.php

Enqueues scripts for the Customizer preview.

_WP_Editors::enqueue_scripts() wp-includes/class-wp-editor.php
Show 39 more Show less

Changelog

VersionDescription
6.3.0 The $in_footer parameter of type boolean was overloaded to be an $args parameter of type array.
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 30 content

    Never worry about cache again!

    This is a little trick I’ve picked up along the way.
    The version of the .js and .css files is made from the time of it’s last update.

    /**
     * Never worry about cache again!
     */
    function my_load_scripts($hook) {
    	// create my own version codes
    	$my_js_ver = date("ymd-Gis", filemtime( plugin_dir_path( __FILE__ ) . 'js/custom.js' ));
    	$my_css_ver = date("ymd-Gis", filemtime( plugin_dir_path( __FILE__ ) . 'style.css' ));
    	
    	// 
    	wp_enqueue_script( 'custom_js', plugins_url( 'js/custom.js', __FILE__ ), array(), $my_js_ver );
    	wp_register_style( 'my_css', 	plugins_url( 'style.css', 	 __FILE__ ), false, $my_css_ver );
    	wp_enqueue_style ( 'my_css' );
    }
    add_action('wp_enqueue_scripts', 'my_load_scripts');

    That way, you will always use the cached versions, except in case the files were changed in the meanwhile, which is the most optimum scenario.

  2. Skip to note 31 content

    When you enqueue script that is dependent on jQuery, note that the jQuery in WordPress runs in noConflict mode, which means you cannot use the common $ alias. You must use the full jQuery instead. Alternately, place your code using the $ shortcut inside a noConflict wrapper.

    jQuery( document ).ready( function( $ ) {
     // $() will work as an alias for jQuery() inside of this function
     [ your code goes here ]
    } );
  3. Skip to note 32 content

    Using a Hook

    Enqueue both scripts and styles from a single action hook.

    /**
     * Proper way to enqueue scripts and styles.
     */
    function wpdocs_theme_name_scripts() {
    	wp_enqueue_style( 'style-name', get_stylesheet_uri() );
    	wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
    }
    add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
  4. Skip to note 33 content

    Link a Theme Script Which Depends on jQuery

    JavaScript files included in themes often require another JavaScript file to be loaded in advance to use its functions or variables. Using the $deps parameter, the wp_enqueue_script() and wp_register_script() functions allows you to mark dependencies when registering a new script. This will cause WordPress to automatically link these dependencies to the HTML page before the new script is linked. If the handles of these dependencies are not registered, WordPress will not link the new script. This example requires the jQuery library for the custom_script.js theme script:

    /**
     * Enqueue a script with jQuery as a dependency.
     */
    function wpdocs_scripts_method() {
    	wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', array( 'jquery' ) );
    }
    add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );
  5. Skip to note 34 content

    I want to add a note to bcworkz comment. When using jquery, in general, this is how the code in a file should be formatted:

    (function( $ ) {
    	"use strict";
    	
    	// javascript code here. i.e.: $(document).ready( function(){} ); 
    })(jQuery);

    It’s a common practice that ensures jQuery runs in no conflict mode and in strict mode.

    Strict mode helps out in a couple ways:

    • It catches some common coding bloopers, throwing exceptions.
    • It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
    • It disables features that are confusing or poorly thought out.
  6. Skip to note 35 content

    Link the script.aculo.us Library

    The following is an example of basic usage which links the script.aculo.us library already included and registered by WordPress with the scriptaculous handle.

    /**
     * Enqueue script.aculo.us.
     *
     * Tha callback is hooked to 'wp_enqueue_script' to ensure the script is only enqueued on the front-end.
     */
    function my_scripts_method() {
     wp_enqueue_script( 'scriptaculous' );
    }
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

    The above example links the script.aculo.us library only on the front-end. If the library was needed within the administration screens, you could use the admin_enqueue_scripts action hook instead, however, this would enqueue it on all the administration screens, which often leads to plugin/core conflicts, ultimately breaking the WordPress administration screens experience. Instead, you should only link it on the individual screens you need it, see the Link Scripts Only on a Plugin Administration Screen section for an example of that.

  7. Skip to note 36 content

    When registering and enqueueing scripts, you don’t need to call wp_register_script() and wp_enqueue_script(). Just call wp_enqueue_script().
    This:

    wp_register_script ( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );
    wp_enqueue_script ( 'custom-script' );

    Should simply be:

    wp_enqueue_script ( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );

    Only register if you don’t know if you’re going to load it immediately.

  8. Skip to note 37 content

    Unmet dependencies will *NOT* be warned

    If dependencies (3rd argument) are not met, the script tag is just not printed and no warnings nor errors are shown.

    This doesn’t seem like a bug, just expected behavior. A mention about this on the docs would suffice to prevent misunderstandings.

    This example will never load /js/example.js

    /**
     * ... enqueue plugin scripts.
     */
    function load_plugin_scripts() {
     wp_enqueue_script(
    		'script-name',
    		plugin_dir_url( __FILE__ ) . '/js/example.js',
    		array('not-existant'),
    		'1.0.0',
    		true
    	);
    }
    add_action( 'wp_enqueue_scripts', 'load_plugin_scripts' );
  9. Skip to note 38 content

    Because of the work on https://core.trac.wordpress.org/ticket/9346, it’s actually safe to call

    wp_enqueue_script

    after the hook “wp_enqueue_scripts” and before the footer, eg when rendering shortcodes or rendering a post’s body.
    Enqueueing stylesheets (css) in this same method has some issues though.
    Scribu gave an example of a shortcode enqueueing a script here: http://scribu.net/wordpress/conditional-script-loading-revisited.html

  10. Skip to note 39 content

    An example of how to enqueue multiple styles and scripts which include the SRI (sub-resource integrity) tag. This is loosely based on this article, but I’ve tried to simplify the code somewhat, particularly given I may want to include and manage many scripts/styles.

    The important thing to note, is the handle specified when enqueuing a style/script, needs to match the handle referenced in the my_add_sri function. Also note, aside from the obvious SRI tag difference, the str_replace method used on scripts in the my_add_sri function, is different to that used on styles.

    /**
    * Load custom CSS and JavaScript.
    */
    add_action( 'wp_enqueue_scripts', 'wpdocs_my_enqueue_scripts' );
    function wpdocs_my_enqueue_scripts() : void {
     // Enqueue my styles.
     wp_enqueue_style( 'wpdocs-bootstrap-style', 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css' );
     wp_enqueue_style( 'wpdocs-datatables-bootstrap-style', 'https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css' );
     
     // Enqueue my scripts.
     wp_enqueue_script( 'wpdocs-bootstrap-bundle-script', 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.bundle.min.js', array(), null, true );
     wp_enqueue_script( 'wpdocs-datatables-bootstrap-script', 'https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/dataTables.bootstrap4.min.js', array(), null, true );
     wp_enqueue_script( 'wpdocs-jquery-datatables-script', 'https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js', array(), null, true ); 
     
     // Add filters to catch and modify the styles and scripts as they're loaded.
     add_filter( 'style_loader_tag', __NAMESPACE__ . '\wpdocs_my_add_sri', 10, 2 );
     add_filter( 'script_loader_tag', __NAMESPACE__ . '\wpdocs_my_add_sri', 10, 2 );
    }
    /**
    * Add SRI attributes based on defined script/style handles.
    */
    function wpdocs_my_add_sri( $html, $handle ) : string {
     switch( $handle ) {
     case 'wpdocs-bootstrap-style':
     $html = str_replace( ' />', ' integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />', $html );
     break;
     case 'wpdocs-datatables-bootstrap-style':
     $html = str_replace( ' />', ' integrity="sha512-PT0RvABaDhDQugEbpNMwgYBCnGCiTZMh9yOzUsJHDgl/dMhD9yjHAwoumnUk3JydV3QTcIkNDuN40CJxik5+WQ==" crossorigin="anonymous" />', $html );
     break;
     case 'wpdocs-bootstrap-bundle-script':
     $html = str_replace( '></script>', ' integrity="sha512-kBFfSXuTKZcABVouRYGnUo35KKa1FBrYgwG4PAx7Z2Heroknm0ca2Fm2TosdrrI356EDHMW383S3ISrwKcVPUw==" crossorigin="anonymous"></script>', $html );
     break;
     case 'wpdocs-datatables-bootstrap-script':
     $html = str_replace( '></script>', ' integrity="sha512-OQlawZneA7zzfI6B1n1tjUuo3C5mtYuAWpQdg+iI9mkDoo7iFzTqnQHf+K5ThOWNJ9AbXL4+ZDwH7ykySPQc+A==" crossorigin="anonymous"></script>', $html );
     break;
     case 'wpdocs-jquery-datatables-script':
     $html = str_replace( '></script>', ' integrity="sha512-BkpSL20WETFylMrcirBahHfSnY++H2O1W+UnEEO4yNIl+jI2+zowyoGJpbtk6bx97fBXf++WJHSSK2MV4ghPcg==" crossorigin="anonymous"></script>', $html );
     break;
     } 
     return $html;
    }
    • As I was trying to use the ‘new’ recommended CDN for Bootstrap 4.5.X (jsDelivr) and stumbled upon how exactly to figure out how to add the SRI tag, I can only commend your solution and the simplification you did to the original code. Thank you!
  11. Skip to note 40 content

    This is not documented, but calling this function with $in_footer being `false` actually registers the script in general as a dependency that should be resolved and output, not just for header. Then, when outputting scripts enqueued for the footer, only the scripts that have not been included yet will be output. This leads to behaviour where a script that is enqueued supposedly in the header will appear in the footer if enqueued after the header has already been process. Therefore, $in_footer should actually read and be understood as $in_footer_only.

  12. Skip to note 41 content

    Because this and wp_enqueue_style uses WP_Scripts::enqueue(), which can take an array of handles as it’s first argument, you can also pass an array of handles into wp_enqueue_script/style:

    /**
     * Enqueue multiple handles
     */
    function enqueue_multiple() {
     wp_enqueue_script( array( 'backbone', 'jquery', 'iris' ) );
    }
    add_action( 'wp_enqueue_scripts', 'enqueue_multiple' );
  13. Skip to note 42 content

    This example is using the new technique of defer or async a script. Also one good practice for versioning of the file is to use the filemtime php native function in order to pass the last modified time of the file as a parameter to the cache.

    $url = get_template_directory_uri() . '/js/functions.js';
    $time = filemtime( get_template_directory() . '/js/functions.js' );
    $args = array( 
     'in_footer' => true,
     'strategy' => 'defer',
    );
    wp_enqueue_script( 'wpdocs-functions', $url, array(), $time, $args );
  14. Skip to note 44 content

    Clearing confusion between all three functions. wp_enqueue_script() , wp_register_script() , and wp_localize_script()

    wp_register_script()::
    Registers a script with WordPress.
    Does not load the script on the page.
    Useful when you want to define a script for later use with specific conditions or dependencies.
    Takes arguments like script handle (unique identifier), script path (URL or relative path to the file), and optional arguments like version number and dependencies on other scripts.

    wp_enqueue_script()::
    Enqueues a script that need to be loaded on the page.
    Can also register the script if it hasn’t been registered before.
    Useful for including scripts you need on a specific page or based on certain conditions (e.g., only on the front-end).
    Takes arguments like script handle (same as used with wp_register_script) and optional arguments like version number, dependencies, and placement (in the header or footer).
    Here’s a key difference:

    wp_enqueue_script can handle both registering and loading a script in one call.
    wp_register_script only registers the script for later use with wp_enqueue_script or another function that might need it.

    wp_localize_script()::
    Does not register or enqueue a script.
    Used to localize a registered script, meaning it injects PHP variables into the script as JavaScript objects.
    Useful for passing data from WordPress (PHP) to your JavaScript code.
    Takes arguments like script handle (of an already registered script), a variable name to hold the data in JavaScript, and the actual PHP data (array or object) you want to pass.

    In short,
    Use wp_register_script to define scripts for later use.
    Use wp_enqueue_script to load scripts on the page (can also register if needed).
    Use wp_localize_script to pass data from PHP to your registered JavaScript code.

  15. Skip to note 46 content

    This documentation should really do a better job defining what a “script” is… Because: is this function meant for enqueueing a .php or html script? No!

    That may seem obvious to a lot of developers, but if you are looking at this documentation, you should be getting some clarity as to what this function should be used for, so I’m writing this to help.

    Apparently, in this case, the term “script” is being used as a program that is not being evaluated by the server, but rather a program that needs to be passed to the client (and evaluated by the browser). Thus in this case, a PHP file that is expected to be evaluated by the server would not be considered a script (even though a lot of people might call it one) and thus it should not be included with wp_enqueue_script() , but included using require_once() or possibly include_once() instead.

  16. Skip to note 47 content

    This example link of custom stylesheet and script with file version version

    function custom_enqueue(){
     //wp_enqueue_style('string $handle', mixed $src, array $deps, mixed $ver, string $meida );
     wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/fatblog.css', array(), '1.0.0', 'all' );
     //wp_enqueue_style('string $handle', mixed $src, array $deps, mixed $ver, bol $in_footer );
     wp_enqueue_script('customjs', get_template_directory_uri() . '/js/fatblog.js', array(), '1.0.0', 'true' );
    }
    add_action('wp_enqueue_scripts', 'custom_enqueue');
  17. Skip to note 49 content

    In some cases, you might want to add scripts as a module. In that case type="module" needs to be added to the tag. This can be done using the script_loader_tag filter hook.

    Modules are a newer feature of JS introduced in ES6 and has many advantages over conventional JS files especially if you are working on a large project. You can read about modules in official documentation.

    function wpdocs_load_module( $tag, $handle ) {
    	if ( 'wpdocs-script-handle' === $handle ) {
    		$tag = str_replace( '<script ', '<script type="module" ', $tag );
    	}
    	return $tag;
    }
    add_filter( 'script_loader_tag', 'wpdocs_load_module', 10, 2 );
  18. Skip to note 50 content

    Replace a parent theme JS (or CSS) entirely:

    function wpdocs_child_enqueue_scripts() {
    	if ( wp_script_is( 'parent-pagination-infinite', 'enqueued' ) ) {
    		wp_dequeue_script( 'parent-pagination-infinite' );
    		wp_enqueue_script( 'child-pagination-infinite', get_stylesheet_directory_uri() . '/pagination-infinite.js', array( 'child-theme-js' ), '1.0.0', true );
    	}
    }
    add_action( 'wp_enqueue_scripts', 'wpdocs_child_enqueue_scripts', 15 );
  19. Skip to note 51 content

    Link a Plugin Script That Depends on script.aculo.us

    This example is intended to be used within a plugin file to register and link a new plugin script that depends on the script.aculo.us library. See the example above for information about dependencies.

    /**
     * Enqueue script with script.aculo.us as a dependency.
     */
    function my_scripts_method() {
    	wp_enqueue_script( 'newscript', plugins_url( '/js/newscript.js' , __FILE__ ), array( 'scriptaculous' ) );
    }
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
  20. Skip to note 52 content

    Link Scripts Only on a Plugin Administration Screen

    This example links a script only on a specific administration screen, as opposed to the scenario described in the paragraph below the code of the first example.

    <?php
    /**
     * Register the plugin script.
     */
    function wpdocs_plugin_admin_init() {
     // Register our script.
     wp_register_script( 'my-plugin-script', plugins_url( '/script.js', __FILE__ ) );
    }
    add_action( 'admin_init', 'wpdocs_plugin_admin_init' );
    /**
     * Add Administration screen for the plugin.
     */
    function wpdocs_plugin_admin_menu() {
     /* Add our plugin submenu and administration screen */
     $page_hook_suffix = add_submenu_page( 'edit.php',	// The parent page of this submenu.
    		__( 'My Plugin', 'my-textdomain' ),				// The submenu title.
    		__( 'My Plugin', 'my-textdomain' ),				// The screen title.
    		'manage_options', 								// The capability required for access to this submenu.
    		'my_plugin-options', 							// The slug to use in the URL of the screen.
    		'wpdocs_plugin_manage_menu' 					// The function to call to display the screen.
    	);
     /*
    	 * Use the retrieved $page_hook_suffix to hook the function that links our script.
    	 * This hook invokes the function only on our plugin administration screen,
    	 * see: https://developer.wordpress.org/reference/hooks/admin_print_scripts-hook_suffix/
    	 */
     add_action( "admin_print_scripts-{$page_hook_suffix}", 'wpdocs_plugin_admin_scripts');
    }
    add_action( 'admin_menu', 'wpdocs_plugin_admin_menu' );
    /**
     * Enqueue registered script in the admin.
     */
    function wpdocs_plugin_admin_scripts() {
     // Link our already registered script to a page.
     wp_enqueue_script( 'my-plugin-script' );
    }
    /**
     * Display callback for the plugin Administration screen.
     */
    function wpdocs_plugin_manage_menu() {
     // Display our administration screen.
    }
  21. Skip to note 53 content

    Not sure if this is the place to report it, but I believe that the Tiny MCE handle that appears on the “Default Scripts Included and Registered by WordPress” table is incorrect. It says tiny_mce, but according to the code that registers the Tiny MCE scripts (https://core.trac.wordpress.org/browser/trunk/src/wp-includes/script-loader.php?rev=45138#L56-L64) should be wp-tinymce.

  22. Skip to note 54 content

    When enqueuing a custom script file that you later want to add some inline JS to using wp_add_inline_script() . It’s always best that you have the custom script enqueuing in the footer by setting the last parameter in the function to true

    wp_enqueue_script( $handle, $src, $deps, $ver, true );

  23. Skip to note 57 content

    The action hook used for loading scripts (wp_enqueue_scripts) is called in the head section of the document, so in order for the script to be loaded on the page, you MUST include the following on your page template:

    get_header();
    • This comment on the action hook stating you must include:

      get_header();

      This is inaccurate. This code fetches the header.php file. What must actually be included in the template is:

      wp_head();

      The confusion here is that most header files contain the wp_head(); hook.

You must log in before being able to contribute a note or feedback.

AltStyle によって変換されたページ (->オリジナル) /