As part of a piece I’m writing for MacUser magazine I’m trying to explain how to easily add jQuery and an associated custom script to a Child Theme in WordPress (v3 onwards). If you’re a designer primarily, the following code snippet may well help you. It assumes you have already made a child theme. With that done, if you haven’t already, make a blank functions.php file alongside your style.css file. Now, inside the functions.php file, paste the following:

< ?php
if ( !is_admin() ) { // instruction to only load if it is not the admin area
   // register your script location, dependencies and version
   wp_register_script('custom_script',
       get_bloginfo('stylesheet_directory') . '/js/custom_script.js',
       array('jquery'),
       '1.0' );

   // enqueue the script
   wp_enqueue_script('custom_script');
}
?>

You’ll now just need to make a folder called ‘js’ inside your theme and create a file called ‘custom_script.js’ within it and stick your jQuery in there. Bish Bosh – Job Done.

If like me, PHP gives you sleepless nights, I’ll try and explain in layman’s terms what the code is actually doing for you (if you don’t care, no worries, be on your way and just be glad it’s working). First of all, we are telling it to ONLY load if not in the Admin screen. This is to make any effects in our custom script not screw up the backend. After all, last thing you want is your back-end screwed…

Next, we register our new script with WordPress:

Us: “Hello WordPress, can I introduce to my friend, ‘Custom Script’? He’s new around here but he’s going to make quite a difference to things I assure you.”

WordPress: “Who? I can’t see a Custom Script? What are you talking about?

Us: “I can assure you, he’s just over here, look, in the /js folder of the stylesheet directory”

WordPress: “Ah, so he, good show!”

Then we tell WordPress what our script needs from WordPress to run correctly e.g.

WordPress: “Are you sure custom-script is alright in that directory all by himself? Is there anything I can help him with?”

Us: “Actually, you’re quite right, he could really do with the jQuery library or he’ll be a little lost” [that’s theย array(‘query’) part]

WordPress: “Right, if that’s all? I’ve got quite a bit of spam to filter with Akismet. I knew something was awry when so many posts said they enjoyed reading your blog…”

Us: “Yes, that’s fine, could you just add…”

WordPress: “Add?”

Us: “Sorry, I forget you like funny terms, ‘enqueue’ the script please?”

WordPress: “As you wish. Good day to you…”

That make sense? No? Oh… Did I mention I don’t get out much these days?