Ashley Cameron Design

Ashley Cameron Design

Shop the Creative Design Market

Good evening

How to add a jQuery script to WordPress

This post was last updated: Sep 3, 2020
jQuerySnippetsWordPress

About a 1 minute read

"There is one thing one has to have: either a soul that is cheerful by nature, or a soul made cheerful by work, love, art, and knowledge."

Friedrich Nietzsche

First, write your script and save the .js file in your theme, preferably in a folder within your theme for organization (e.g. /your-theme/js/your-script.js)


1
2
3
jQuery(function($) {
  $('#nav a').last().addClass('last');
})

Next, open functions.php within your theme


1
2
3
4
5
6
7
8
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script(
        'your-script', // name your script so that you can attach other scripts and de-register, etc.
        get_stylesheet_directory_uri() . '/js/your-script.js', // this is the location of your script file
        array('jquery') // this array lists the scripts upon which your script depends
    );
}

Here’s the script without comments:


1
2
3
4
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script('your-script', get_stylesheet_directory_uri() . '/js/your-script.js', array('jquery'));
}