How to Correctly Enqueue jQuery in WordPress

Enqueuing scripts properly in WordPress is essential for preventing plugin conflicts, maintaining site performance, and ensuring dependencies load in the correct order. This guide explains how to use WordPress's built-in script loading system to register and load custom jQuery scripts using the standard wp_enqueue_scripts action hook and address WordPress's default noConflict mode.

The Correct Function: wp_enqueue_script()

Never add scripts directly to your theme's header.php or footer.php file using standard HTML <script> tags. Instead, add your enqueue function to your theme’s functions.php file or inside a custom plugin using the wp_enqueue_script() function.

WordPress includes its own copy of jQuery by default. When you enqueue a custom script that relies on jQuery, you simply declare 'jquery' as a dependency in the dependency array. WordPress will automatically load its core jQuery library before your custom script runs.

Implementation Example

Add the following code to your theme's functions.php file:

function my_theme_enqueue_scripts() {
    wp_enqueue_script(
        'custom-script',                                        // Unique script handle
        get_template_directory_uri() . '/js/custom-script.js',  // Script source path
        array('jquery'),                                        // Dependencies
        '1.0.0',                                                // Script version
        true                                                    // Load in footer (true) or head (false)
    );
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

If you are working inside a child theme, replace get_template_directory_uri() with get_stylesheet_directory_uri().

Handling WordPress jQuery's noConflict Mode

WordPress loads jQuery in noConflict mode to prevent conflicts with other JavaScript libraries. This means the standard shortcut $ is disabled globally, and you cannot use $('#element') directly in your scripts.

To safely use the $ shortcut in your custom JavaScript file (custom-script.js), wrap your code in a self-executing anonymous function or pass $ into the document ready handler:

jQuery(document).ready(function($) {
    // Inside this function, the $ alias works normally
    $('body').addClass('jquery-loaded');
});

Alternatively, you can use an immediately invoked function expression (IIFE):

(function($) {
    // $ is safely mapped to jQuery here
    console.log('Script loaded safely');
})(jQuery);

By following this approach, your scripts remain fully compatible with WordPress updates, third-party plugins, and modern web performance best practices.