Using jQuery in WordPress Theme

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Let’s say that you are altering a WordPress theme and you need jQuery to run a slider or another widget that you are building in your theme.   For the purpose of this tutorial, we will add some jQuery code to the footer of the theme.

There is no need to add in the jQuery library.  WordPress 4.1 is already using the jQuery library.  Do a “view source” in your browser on your WordPress site and you will see …

jquery already in wordpress

jquery already in wordpress

But if you just try using jQuery by putting the following jQuery script in footer.php of your theme …

attempt at adding jQuery

attempt at adding jQuery

You get a script error …

“Uncaught TypeError: undefined is not a function”

It does not recognize the usual jQuery $ object.  That is because jQuery is in “no conflict mode”.  So you have to use the jQuery object instead of the shorthand $ object as in …

jQuery working

jQuery working

You see that jQuery is working because the console.log output correctly in the browser’s console.

If you want to use the $ jQuery shortcut object, you can do “Immediately-Invoked Function Expression (IIFE)” in a Javascript closure as in …

use jQuery in WordPress like this

use jQuery in WordPress like this

Our other tutorial explains better this syntax.