How to properly use jQuery $ in WordPress themes/plugins

Solution 1:

In WordPress, when you enqueue jQuery:

  • By default, you must use jQuery instead of $ to avoid conflicts with other libraries.
  • Wrapping your code in a function works fine, or you can load jQuery differently (though this is generally not recommended).
  • If you want to use $(document).ready(), you can safely pass $ into the function:

jQuery(function($) {
    // Your code using $ safely here
});

✅ Explanation:

  • This ensures $ references jQuery only within your function, avoiding conflicts with other scripts.
  • This is the recommended approach for WordPress-compatible jQuery code.

Solution 2:

You can safely use $ in WordPress by wrapping your code like this:


jQuery(document).ready(function($) {
    // $ now references jQuery safely
    var body = $('body');
});

✅ Explanation:

  • WordPress includes jQuery in noConflict() mode to prevent $ from colliding with other JavaScript libraries.
  • This means the global $ shortcut for jQuery is not available by default.
  • By passing $ into the function as shown, you can safely use $ within your code without interfering with other scripts.

📖 Reference:

  • See wp-includes/js/jquery/jquery.js where WordPress sets jQuery to noConflict mode.

Solution 3:

You can safely use $ in WordPress by wrapping your code in an immediately invoked function expression (IIFE):


;(function($) {
    // Your code here, $ safely references jQuery
})(jQuery);

✅ Explanation:

  • The semicolon (;) at the beginning prevents issues if previous scripts are not terminated properly.
  • $ inside the closure is a safe reference to jQuery, avoiding conflicts with other libraries.
  • This is a common pattern used in WordPress and other CMS environments where jQuery runs in noConflict() mode.

📖 Reference: