How to use jQuery “$” in WordPress

If you add javascript into WordPress, you will certain try execute some jQuery functions sooner or later.

And, you will get an error telling that $ is undefined.

I think that jQuery embedded into wordpress do not declare the “$” variable, as it may confuse some users with all the $ server-side variables from PHP.

All jQuery functions can be run using “jQuery” variable instead of “$”.

But, if you want to use “$” as you did before, be warned that just typing:
$ = jQuery;
can interfere with some existing functions that may use the $ variables for other purposes.

So, what I propose is to encapsulate all your functions inside a self-called function like this:

(function($){
   ...
   $('body').addClass("cool");
   ...
 })(jQuery);

You put all your code inside that function, the “$” is available, and it doesn’t interfere with all other code.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.