Code Snippet to Enqueue Custom Scripts and Styles in WordPress

Tomasz W Jan 5, 2025 Enqueuing Scripts and Styles
How do I add my own scripts and styles to my website?
What is the proper method to enqueue custom JavaScript and CSS files in WordPress using the `wp_enqueue_script` and `wp_enqueue_style` functions?
Andy answered Jan 5, 2025

Enqueuing Custom Scripts and Styles

Custom Code Solution

The following code should be placed in your theme's functions.php file or in a custom functionality plugin.

Basic script and style enqueuing for your theme:

function theme_enqueue_assets() {
    // Enqueue CSS
    wp_enqueue_style(
        'theme-main-style',
        get_template_directory_uri() . '/assets/css/main.css',
        array(),
        '1.0.0'
    );

    // Enqueue JavaScript
    wp_enqueue_script(
        'theme-main-script',
        get_template_directory_uri() . '/assets/js/main.js',
        array('jquery'),
        '1.0.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'theme_enqueue_assets');

Enqueuing with conditional loading (only on specific pages):

function theme_conditional_assets() {
    // Load contact page CSS only on contact page
    if (is_page('contact')) {
        wp_enqueue_style(
            'contact-style',
            get_template_directory_uri() . '/assets/css/contact.css',
            array(),
            '1.0.0'
        );
    }

    // Load shop scripts only on WooCommerce pages
    if (function_exists('is_woocommerce') && is_woocommerce()) {
        wp_enqueue_script(
            'shop-script',
            get_template_directory_uri() . '/assets/js/shop.js',
            array('jquery'),
            '1.0.0',
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'theme_conditional_assets');

Passing PHP variables to JavaScript:

function theme_localize_script() {
    wp_localize_script(
        'theme-main-script',
        'themeData',
        array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'siteUrl' => get_site_url(),
            'nonce'   => wp_create_nonce('theme-nonce')
        )
    );
}
add_action('wp_enqueue_scripts', 'theme_localize_script');

Important Notes:

  1. File paths assume this structure:

    • /wp-content/themes/your-theme/assets/css/main.css
    • /wp-content/themes/your-theme/assets/js/main.js
  2. Parameters for wp_enqueue_script():

    • Handle (unique identifier)
    • File path
    • Dependencies array
    • Version number
    • Load in footer (boolean)
  3. Parameters for wp_enqueue_style():

    • Handle (unique identifier)
    • File path
    • Dependencies array
    • Version number

Plugin Alternative

If you prefer a plugin solution, consider:

However, the custom code solution is recommended for better performance and control.