Adding custom jQuery scripts to a WordPress Child Theme

I have a moderate amount of experience building WordPress child themes, and over the last few days I’ve really struggled with figuring out how to begin getting some custom jQuery scripts integrated into this one. I used the codex and several other resources, but I couldn’t find a concise, straightforward set of instructions that briefly explain how to plug a custom script file into a child theme, so I’ve decided to make my own

First, you must have successfully set up a child theme. Basically, you just need to make a folder and put a few specific lines into a style.css so that WordPress knows that it is a derivative of a parent theme. The Codex is likely the best resource for how to do this – it’s not hard.

If you’re like me, and you’ve set up the child theme and styled it like a mash up of Tron and an 80’s hair metal band, you’re ready to get your scripting on. Set up a simple script file and place it in a folder in your child theme’s directory. I always name this folder ‘js’ if helps make sense of the following snippets. I think it’s helpful to use a basic test snippet just to ensure that the script is loading

var $j = jQuery.noConflict();
alert(‘Script successfully loaded’);

It’s not critical that you use no conflict mode, but writing out jQuery all the time just feels…weird. After you’ve got your test script, create a file called functions.php and place it in your child theme’s folder. Use the following as a template for that file

function add_my_scripts(){
get_bloginfo(‘stylesheet_directory’).’/js/yourscript.js’, array(‘jquery’),’1.0′);
add_action(‘init’, ‘add_my_scripts’);

You can essentially treat this code like black magic, but suffice it to say that it creates a little function called ‘add_my_scripts’ which registers and enqueues your custom script file, and attaches it to WordPress’ init hook. The other significant thing to note about this snippet is that ‘getblog_info(‘stylesheet_directory’)’ will ensure that the url used to find your script is derived from your child theme’s stylesheet. After you’ve got this working, I really suggest checking the codex to get better sense of what all that means. Thanks!

4 responses to “Adding custom jQuery scripts to a WordPress Child Theme”

  1. Jason the Saj


    Can you show how/where I should then call the function?

    Say I wanted to use JQuery to alter my footer with random messages, or even just pop up an alert. How would I call it?

  2. m3325xb

    I there is syntax error in your script a this line :
    I can’t get it work.
    Please help.

Leave a Reply