Using WordPress ‘wp_enqueue_scripts’ PHP action

The wp_enqueue_scripts WordPress PHP action is used to enqueue scripts and styles that should appear on the front end of your website.

Usage

function your_theme_enqueue_style() {
    // your custom code here
    wp_enqueue_style('your-style-handle', 'path/to/style.css', false);
}

function your_theme_enqueue_script() {
    // your custom code here
    wp_enqueue_script('your-script-handle', 'path/to/script.js', false);
}

add_action('wp_enqueue_scripts', 'your_theme_enqueue_style');
add_action('wp_enqueue_scripts', 'your_theme_enqueue_script');

Parameters

  • handle (string) – A unique identifier for the script or style being enqueued.
  • src (string) – The URL of the script or style being enqueued.
  • deps (array) – An array of handles the enqueued script or style depends on. Default is an empty array.
  • ver (string|bool|null) – The version of the script or style. Default is false.
  • in_footer (bool) – For scripts only, whether to enqueue the script in the footer. Default is false.
  • media (string) – For styles only, the media attribute for the stylesheet link. Default is ‘all’.

More information

See WordPress Developer Resources: wp_enqueue_scripts

Examples

Enqueue a Custom CSS File

Enqueue a custom CSS file named ‘custom-style.css’ in your theme folder.

function enqueue_custom_style() {
    wp_enqueue_style('custom-style', get_template_directory_uri() . '/custom-style.css');
}

add_action('wp_enqueue_scripts', 'enqueue_custom_style');

Enqueue a Google Font

Enqueue the Google Font ‘Roboto’ to be used in your theme.

function enqueue_google_font() {
    wp_enqueue_style('google-font-roboto', 'https://fonts.googleapis.com/css?family=Roboto&display=swap');
}

add_action('wp_enqueue_scripts', 'enqueue_google_font');

Enqueue a jQuery Plugin

Enqueue a jQuery plugin named ‘jquery-plugin.js’ in your theme folder.

function enqueue_jquery_plugin() {
    wp_enqueue_script('jquery-plugin', get_template_directory_uri() . '/jquery-plugin.js', array('jquery'), '1.0', true);
}

add_action('wp_enqueue_scripts', 'enqueue_jquery_plugin');

Enqueue a Script with Localized Data

Enqueue a script named ‘localized-script.js’ and pass data to it from PHP.

function enqueue_localized_script() {
    wp_enqueue_script('localized-script', get_template_directory_uri() . '/localized-script.js', array('jquery'), '1.0', true);
    wp_localize_script('localized-script', 'localizedData', array('ajax_url' => admin_url('admin-ajax.php')));
}

add_action('wp_enqueue_scripts', 'enqueue_localized_script');

Conditionally Enqueue a Script

Enqueue a script named ‘conditional-script.js’ only on the homepage.

function enqueue_conditional_script() {
    if (is_front_page()) {
        wp_enqueue_script('conditional-script', get_template_directory_uri() . '/conditional-script.js', array(), '1.0', true);
    }
}

add_action('wp_enqueue_scripts', 'enqueue_conditional_script');