While developers have been integrating jQuery with WordPress for several years now, there is still a fair amount of confusion about how to probably add it to your WordPress site. Based on research, experience and what seems to be an overall consensus, I have outlined below the best way to use jQuery in WordPress.
Deregister WordPress jQuery and register your own version
By default, WordPress comes prepacked with jQuery. However, it is best practice to deregister the WordPress core version of jQuery and register the version that you would like to use. In the example below, I want to implement the latest version of the jQuery CDN using the Google API. To do so, place the code below in your
Create a file and put it in a JS folder
Now that you have replaced the default WordPress version of jQuery with your own, the next thing is to create a file with your jQuery code. The easiest way is to just create a folder in your public_html folder called ‘js’. After creating the folder, create another file in that folder, which represents the name of your code. In the example below, I have created a file called ‘fadein.js’, which has been placed in my ‘js’ folder. Below, you can see the code that I have added to
Enqueue your jQuery file in functions.php
The last thing we need to do is enqueue our
fadein.js in the
functions.php file. Keep in mind that rather than enqueuing the file, we could just simply add it as a script in our footer. However, the consensus seems to be the best WordPress practice is to enqueue it in the
functions.php file. In the example below, you can see the way in which I have enqueued it.
Although implementing jQuery on your WordPress site may be somewhat intimidating at first and cause a few headaches, it is totally worth the effort. Even just adding a few modules of jQuery code can really make for a more dynamic site and serve as a tool to make your website standout. Best of all, there is an endless amount of literature, code snippets and tutorials on jQuery online.