How to use jquery in WordPress?

Used before category names. Blog WordPress WordPress Development

WordPress is old enough, yet the method of adding scripts properly to themes and plugins still remains a mystery for many developers. Using JQuery in WordPress is not exceptional.

jQuery is a fast, small, and feature-rich JavaScript library for creating unique, dynamic, and engaging websites. This library is one of the most used libraries of JavaScript.

To use jQuery in your WordPress plugins and themes, all you need to do is enqueue the script. But WordPress comes pre-loaded with jQuery, which you can use with your code without enqueue it.

WordPress’ jQuery also has a “compatibility mode,” which is a mechanism for avoiding conflicts with other language libraries. This means you cannot use the “$” sign directly. Instead, when writing jQuery for WordPress you need to use “jQuery“.

Create your JavaScript file in your theme in “assets -> js -> custom.js“. Then open the “functions.php” file and add the below code.

if (!function_exists('hs_enqueue_scripts')) {
    function hs_enqueue_scripts()
        wp_enqueue_script('hs-main-script', esc_url(get_template_directory_uri() . '/assets/js/custom.js'), array('jquery'), '1.0.0', true);

    add_action('wp_enqueue_scripts', 'hs_enqueue_scripts');

As you see we add “array(‘jquery’)” to tell the WordPress that, add load “custom.js” file after jquery file. Now you can open the “custom.js” file and write your jQuery code.

jQuery(window).load(function() {

How to use $ instead of JQuery

As we told you, you can not use $ sign directly. The problem is, writing jQuery a gazillion times takes longer, makes it harder to read, and can bloat your script. Use the below code instead.

  //you can now use $ as your jQuery object.
  var body = $( 'body' );

Add jQuery to WordPress website by plugin

There are plugins you can use that will help you incorporate jQuery into your website.

Advanced Custom Fields turns WordPress sites into a fully-fledged content management system by giving you all the tools to do more with your data.

Customize your WordPress site’s appearance by easily adding custom CSS and JS code without even having to modify your theme or plugin files. This is perfect for adding custom CSS tweaks to your site.