Code Snippet to Enqueue Custom Scripts in WordPress

Marek K Jan 8, 2025 Enqueue Scripts
How can I add some special features to my website using extra tools or scripts?
What is the correct method to enqueue custom JavaScript files in WordPress using the `wp_enqueue_script` function, and how can I ensure they load in the right order?
Andy answered Jan 8, 2025

Enqueuing Custom Scripts in WordPress

Custom Code Solution

This solution shows how to properly enqueue JavaScript files in WordPress. Place this code in your theme's functions.php file or in a site-specific plugin:

Basic script enqueuing with WordPress dependencies:

function enqueue_custom_scripts() {
    wp_enqueue_script(
        'custom-script',                                    // Unique handle
        get_template_directory_uri() . '/js/custom.js',     // Path to your JS file
        array('jquery'),                                    // Dependencies
        '1.0.0',                                           // Version number
        true                                               // Load in footer
    );
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');

If you need to pass PHP variables to your JavaScript:

function enqueue_script_with_data() {
    wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0', true);
    
    $script_data = array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'security' => wp_create_nonce('custom-security-nonce')
    );
    
    wp_localize_script('custom-script', 'customData', $script_data);
}
add_action('wp_enqueue_scripts', 'enqueue_script_with_data');

To enqueue multiple scripts in the correct order:

function enqueue_multiple_scripts() {
    // First script
    wp_enqueue_script('script-one', get_template_directory_uri() . '/js/script-one.js', array(), '1.0.0', true);
    
    // Second script (depends on first script)
    wp_enqueue_script('script-two', get_template_directory_uri() . '/js/script-two.js', array('script-one'), '1.0.0', true);
    
    // Third script (depends on jQuery and second script)
    wp_enqueue_script('script-three', get_template_directory_uri() . '/js/script-three.js', array('jquery', 'script-two'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_multiple_scripts');

Key Points:

  • Scripts should be placed in your theme's /js/ directory
  • Always use wp_enqueue_scripts hook for frontend scripts
  • Use dependencies array to manage loading order
  • Set version number to help with cache busting
  • Use true as the last parameter to load scripts in footer (recommended)

Plugin Alternative

If you prefer a plugin solution, consider:

Best Practices:

  1. Always check if scripts are already enqueued
  2. Use minified versions for production
  3. Load scripts in footer when possible
  4. Include version numbers for cache control
  5. Use dependencies array to manage load order
  6. Follow WordPress coding standards