I was working on a feature for Arturo to add (or enqueue) a script only if a certain function was used on a page. The problem was, that you can’t use wp_enqueue_script() after wp_head() since you can’t hook into an action that has already completed. It took some digging around to figure this one out so I thought it would be best to share it.

The power of $wp_scripts

There really isn’t that much power to $wp_scripts but I thought that would make for a good section title. $wp_scripts is a global variable that contains all the script information that will be added to your page. Of course, you can’t add a script to your header after the header has already run, so this will only work when you need to add a script to your footer. There is a lot going on with $wp_scripts but for our purposes, we only want to hook into the part that contains the info for the scripts that will appear in the footer.

First things first, let register our script in the functions.php file:

function our_script_init() {
   $template_url = get_template_directory_uri();
   wp_register_script('our_script_js', $template_url.'/js/our_script.js', array( 'jquery' ),'',true);
}		
add_action( 'init', 'our_script_init' );

For more info on wp_register_script() check out the CODEX.

Now that our script is registered, we can create a function that will hook into $wp_scripts and add our script only if the function is being used.

Here is our simple function:

function simple_function() {
   global $wp_scripts;
   $wp_scripts->in_footer[] = 'our_script_js';
}

Of course, you can add a lot more to the function, but for the sake of just using it to add the script, It is really that simple. Now, when you use simple_function() on a page, the script that we registered will be added to the footer script queue.