Follow Join

WordPress Theming: Injecting some JavaScript 12 years ago

The third part in my adventures in theming

  1. Multiple WordPress Development Environments
  2. Building a Custom WordPress Theme

Get Inside That Header

The first thing that needs to get done is getting at the segment of code that builds the <head>. I went inside my thematic/library/extensions/header-extensions.php file and located the thematic_head_scripts() section. I copy that code and head over into my child theme's functions.php file.

I then declare the function childtheme_override_head_scripts() inside and paste in the code. Now, this next step is really up to you, I personally wiped out most of the code except for the enqueue for jquery when not an admin. For reference, it looks a little like this:

 // inject custom scripts into header
 function childtheme_override_head_scripts() {     
   // load jquery when is not admin
   if ( !is_admin() ) {
     wp_enqueue_script('jquery');
   }
 }
 add_filter('childtheme_override_head_scripts','childtheme_head_scripts');

Now boom, you are inside the <head> fiddling with <scripts>.

Inject some JavaScript

So that gets us far, but not to the very end. I next wanted to add some custom code between a <head> block. All one has to do is echo whatever one desires. So furthering the example I have going on above, let's now add a file main.js to the queue that will contain any custom code that we may want to work with whenever the user is at the home or landing page.

First one will want to create the file main.js in the themes/yourtheme/library/scripts/ directory. Then all you need to do is add some code to your override function:

 // inject custom scripts into header
 function childtheme_override_head_scripts() {     
   // load jquery when is not admin
   if ( !is_admin() ) {
      wp_enqueue_script('jquery');
   }

   if (is_home() || is_front_page()) {
      // handy trick because get_template_directory_uri() 
      // returns thematic path         
      $childscriptdir = get_stylesheet_directory_uri();  
      $childscriptdir .= '/library/scripts/';
      wp_enqueue_script('main',$childscriptdir.'main.js');
    }
 }
 add_filter('childtheme_override_head_scripts','childtheme_head_scripts');

The conditional statement will make sure that the viewer is only at the landing page or front page. Next comes a trick to get your child theme's directory. If you were building a theme from scratch and not as a child off of a parent, use get_template_directory_uri() instead.

After setting up your path you can then use wp_enqueue_script() (WordPress function reference) to enqueue the file for the header.

Done!

You got your custom scripts into your <head>. Hope you also get to enjoy some of the other little tricks thrown in there. Good luck!