wp enqueue scripts
WordPress has an enqueuing system for adding local/remote scripts along with styles to prevent conflicts with plug-ins. Since most users run WordPress with a theme and several plugins, developers are advised to use the correct method of loading scripts into WordPress.
Descriptions
wp_enqueue_scripts is the proper hook to use when enqueuing items that are meant to appear on the front end. Despite the name, it is used for enqueuing both scripts and styles.
Example
1 2 3 4 5 6 7 8 9 10 |
function themeslug_enqueue_style() { wp_enqueue_style( 'core', 'style.css', false ); } function themeslug_enqueue_script() { wp_enqueue_script( 'my-js', 'filename.js', false ); } add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' ); add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' ); |
Enqueue a script – Code Details
1 |
wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false ) |
Descriptions
Registers the script if $src provided (does NOT overwrite), and enqueues it.
Parameters
$handle
(string) (Required) Name of the script. Should be unique.
$src
(string) (Optional) Full URL of the script, or path of the script relative to the WordPress root directory.
Default value: ”
$deps
(array) (Optional) An array of registered script handles this script depends on.
Default value: array()
$ver
(string|bool|null) (Optional) 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 value: false
$in_footer
(bool) (Optional) Whether to enqueue the script before
2 Comments
nice share!
Thank you for such a good explanation.
Nice explanation.