Helping you build a better website
(and other interesting web stuff)

Silva Web Designs - Blog

Can’t use jQuery in WordPress? Find out how…

Have you ever tried using jQuery in WordPress and couldn’t find out why it wasn’t working?

The reason behind this is simple and is probably not working because your code looks something like this example below:-


So why does this not work?

There are different ways to fix this, the ‘best’ way of fixing this is by editing the ‘enqueue’ setting which is usually within your functions.php file:-


The code above is typically the default setting for WordPress Themes. This means that the usual ‘$’ shortcut for jQuery doesn’t work.

Most of the developers of plugins and theme developers are already aware of this, and they use ‘jQuery’ as apposed to ‘$’ to be safe and to ensure the plugin will be compatible.

/**** Typical jQuery ***/

/*** "Safe" method of jQuery in WordPress ***/

The most frustrating thing about using ‘jQuery’ as opposed to ‘$’ everywhere within your WordPress files is that it doesn’t look as clean which makes it harder to read and that it bloats the size of your website.

If the script is being loaded in the footer (which you should be doing in the vast majority of cases) you can wrap the code in an anonymous function where you pass in jQuery to be mapped to $ as follows:-

(function($) {
	// $ Works! You can test it with next line if you like
	// console.log($);
})( jQuery );

If you really need to load the scripts in the header, you will probably need to use a document ready function anyway, so you can just pass in $ as follows:-

jQuery(document).ready(function( $ ) {
	// $ Works! You can test it with next line if you like
	// console.log($);

Post by Silva Web Designs


It’s good to share

Join the discussion