WordPress Dev: Properly using JQuery and the $

Post author: Adam VanBuskirk
Adam VanBuskirk
5/13/23 in

For compatibility reasons with other libraries, WordPress enqueues and uses JQuery instead of the shorthand dollar sign. Below is how this works and why, including a code example.

Enqueue jQuery in WordPress

In WordPress, it’s important to properly enqueue jQuery to ensure that it is loaded in the correct order and that there are no conflicts with other scripts. Here’s an example code snippet to enqueue jQuery in WordPress:

function my_custom_scripts() {
    wp_enqueue_script( 'jquery' );
add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );

This code should be added to your functions.php file in your theme or child theme. This will enqueue jQuery in the head section of your website. If you want to enqueue jQuery in the footer, you can add the true parameter as the fourth argument, like so: wp_enqueue_script( 'jquery', '', array(), '', true );

Use jQuery in a script

Once you’ve enqueued jQuery in WordPress, you can use it in a script snippet. Here’s an example code snippet of how to use jQuery to toggle the visibility of an HTML element on a button click:

<button id="myButton">Click me!</button>
<div id="myDiv" style="display: none;">This is some hidden content.</div>

    jQuery(document).ready(function($) {
        $('#myButton').click(function() {

In this example, we first create a button with the ID myButton and a div with the ID myDiv that has a display style set to none. We then use jQuery to toggle the visibility of myDiv when the button is clicked.

The jQuery(document).ready() function ensures that the jQuery code is only executed when the page has finished loading, and the $ symbol is passed as a parameter to the function to ensure that it works with jQuery even if another library is using the $ symbol.

Overall, this code snippet demonstrates how to properly enqueue jQuery in WordPress and how to use it in a script snippet to perform some functionality.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

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

Read Next

© 2024 Menyu LLC