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:
- Always check if scripts are already enqueued
- Use minified versions for production
- Load scripts in footer when possible
- Include version numbers for cache control
- Use dependencies array to manage load order
- Follow WordPress coding standards