Quick fix for jQuery “Uncaught TypeError: $ is not a function” in WordPress

jQuery is an old library used on millions of websites. Likewise, WordPress used and still uses it extensively in plugins and themes. While I strongly advise everyone to switch off the usage of this library, we still have to support it in old projects.

One of the common problems I see lately is the jQuery $ (dollar) variable not being recognized. As a result, you may see a message like this in the dev console:

Preferred solution if you have access to JS code and have the permission to edit:

Uncaught TypeError: $ is not a function

There are dozens of solutions to this problem. But most of them require modifying the existing code. Replacing the $ variable with jQuery or wrapping it in a function like this:

(function($){
    // Your normal jQuery code goes here
})(jQuery);

… and many other similar solutions.

Doing so is preferred when you have access to the code and you are allowed to edit it. But when you can’t or don’t want to change it, you can achieve it with this workaround as follows.

The alternative solution when you may not have access to JS code:

Add this in the functions.php file of your theme, or in a new plugin.

add_action('wp_enqueue_scripts', function(){
	wp_add_inline_script('jquery', 'var $ = jQuery.noConflict();');
});

What this does, is adding the no conflict jQuery code, which re-registers the dollar variable.

It should do the trick.

One last note, if the above code does not work for you. Check the source code. You may have two or more versions of jquery enqueued on the page. Make sure to leave only one.

Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

  • Hattori21 3 months ago

    Worked at once, thanks for the light tip (not having to read thousands of lines of text unfocusing it’s a bust).

    Congrats as well for the design of the site, it is very pleasant to use and very innovative!

    Cheers!

Your email address will not be published. Required fields are marked *