Using WordPress ‘wp_enqueue_script()’ PHP function

The wp_enqueue_script() WordPress PHP function is used to enqueue a script, registering it if a source is provided, and ensuring that it doesn’t overwrite existing scripts.

Usage

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

Parameters

  • $handle (string) – Required. The unique name of the script.
  • $src (string) – Optional. The full URL or relative path of the script. Default: ”.
  • $deps (string[]) – Optional. An array of registered script handles that this script depends on. Default: array().
  • $ver (string|bool|null) – Optional. The script version number for cache busting, or false for the WordPress version. Default: false.
  • $in_footer (bool) – Optional. Whether to enqueue the script before </body> instead of in the <head>. Default: false.

More information

See WordPress Developer Resources: wp_enqueue_script()

Examples

Enqueue a custom script

Enqueue a custom script called ‘my-script.js’ located in the ‘js’ folder of your theme.

function my_theme_enqueue_scripts() {
    wp_enqueue_script('my-script', get_template_directory_uri() . '/js/my-script.js', array('jquery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

Load a Google Maps API script

Enqueue the Google Maps API script with an API key.

function load_google_maps_api() {
    wp_enqueue_script('google-maps-api', 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY', array(), null, true);
}
add_action('wp_enqueue_scripts', 'load_google_maps_api');

Enqueue a script with dependencies

Enqueue a script that depends on both jQuery and another custom script.

function enqueue_dependent_script() {
    wp_enqueue_script('dependent-script', get_template_directory_uri() . '/js/dependent-script.js', array('jquery', 'my-script'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_dependent_script');

Enqueue a script without a version number

Enqueue a script without a version number, preventing cache busting.

function enqueue_script_no_version() {
    wp_enqueue_script('no-version-script', get_template_directory_uri() . '/js/no-version-script.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_script_no_version');

Enqueue a script to be placed before the </body> tag instead of in the <head>.

function enqueue_footer_script() {
    wp_enqueue_script('footer-script', get_template_directory_uri() . '/js/footer-script.js', array(), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_footer_script');