If you’ve ever added custom JavaScript in WordPress and noticed your jQuery code doesn’t work as expected, it’s likely because WordPress runs jQuery in “noConflict” mode.

In this mode, the $ shorthand is not available globally, and you must use a jQuery wrapper to safely and consistently write your code.

In this quick tutorial, you’ll learn how to properly use the jQuery wrapper in WordPress, with a working example.

⚠️ Why $() Doesn’t Work by Default in WordPress

WordPress includes jQuery in noConflict mode to prevent conflicts with other JavaScript libraries (like MooTools or Prototype) that also use the $ symbol.

That means this code will likely break in WordPress:

$(document).ready(function() {
    // Your code here
});

Instead, you need to use the WordPress-safe version.

✅ The Correct Way: Use the jQuery Wrapper

Wrap your code like this to avoid issues:

jQuery(document).ready(function($) {
    // Now you can safely use $ inside this function
    $('.menu-toggle').click(function() {
        $('.main-menu').slideToggle();
    });
});

🧠 What’s happening here?

  • We’re passing $ as a parameter to the anonymous function.
  • Inside the function, $ now refers to jQuery, just like you’d expect.
  • Outside this wrapper, $ is still undefined (or used by another library).

🗂 Where to Put This Code

You can add this code to:

  • A custom JS file enqueued in your theme or plugin
  • A <script> tag inside your page or footer
  • A Gutenberg HTML block (for testing purposes only)

📦 Example: Enqueue a Custom jQuery Script in WordPress

Here’s how to properly enqueue your JavaScript file with jQuery as a dependency in your theme:

function custom_enqueue_scripts() {
    wp_enqueue_script(
        'custom-js',
        get_template_directory_uri() . '/js/custom.js',
        array('jquery'), // Declare jQuery as a dependency
        null,
        true
    );
}
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');

Then in custom.js, you can safely write:

jQuery(document).ready(function($) {
    $('.alert-button').click(function() {
        alert('Button clicked!');
    });
});

🧩 Optional: Vanilla JS vs jQuery

Modern WordPress themes often rely more on vanilla JavaScript, but jQuery is still widely used in themes, page builders, and plugins.

So if you’re customizing themes like Astra, GeneratePress, or Divi—or building quick frontend behaviors—jQuery is still useful.

🎯 Final Thoughts

When working in WordPress, always wrap your jQuery code using the method shown above to avoid conflicts and ensure cross-theme compatibility.

It’s a small change, but it can save you a lot of debugging headaches!