How to Alias jQuery to $ in WordPress

By default, WordPress loads jQuery in "no-conflict" mode (jQuery.noConflict()) to prevent compatibility issues with other JavaScript libraries that might also use the dollar sign ($). Consequently, attempting to use the standard $ selector directly in your custom script will trigger an Uncaught TypeError: $ is not a function error. This guide demonstrates the standard, safe methods for re-aliasing jQuery to $ within your WordPress script files without breaking core functionality.

Method 1: The Immediately Invoked Function Expression (IIFE)

The most robust and universally recommended approach is to wrap your code in an Immediately Invoked Function Expression (IIFE). By passing jQuery into the function as an argument and naming the parameter $, you can freely use the $ symbol anywhere inside the wrapper.

(function($) {
    'use strict';

    // $ is now safely mapped to jQuery inside this block
    $(document).ready(function() {
        $('body').addClass('custom-js-loaded');
        
        $('.my-button').on('click', function(e) {
            e.preventDefault();
            console.log('Button clicked!');
        });
    });

})(jQuery);

This method scopes the $ alias exclusively to the inside of the function, ensuring global compatibility is maintained across your WordPress installation.


Method 2: Passing $ Through Document Ready

If your script only needs to execute once the Document Object Model (DOM) is fully loaded, you can pass $ directly into the jQuery(document).ready() callback function.

jQuery(document).ready(function($) {
    // $ refers to jQuery inside this callback
    $('header').css('background-color', '#f0f0f0');
});

You can also use the shorter equivalent syntax:

jQuery(function($) {
    // Shorthand document ready
    $('.toggle-menu').on('click', function() {
        $('.nav-links').toggleClass('active');
    });
});

Ensure Proper Script Enqueueing

For any of these methods to work, your script must load after jQuery. Always declare jquery as a dependency in your functions.php file when calling wp_enqueue_script():

function my_theme_enqueue_scripts() {
    wp_enqueue_script(
        'custom-script',
        get_template_directory_uri() . '/js/custom-script.js',
        array('jquery'), // Declares jQuery as a dependency
        '1.0.0',
        true // Loads script in footer
    );
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

Declaring the dependency guarantees that WordPress loads the core jQuery library before your custom file executes.