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

"We cannot solve our problems with the same thinking we used when we created them."

Albert Einstein

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'));
}