Enqueue Javascript in WordPress: What I wish someone told me

I wanted some javascript on the front page to display a button that toggled the visibility of a doodle at the bottom of the screen. In a normal website, the necessary javascript is written in a separate file which is then called with <script> tags in the head of the html file. How do you get these <script> tags into the head of a WordPress page?

The Codex and user forums tell us that hacking the header template with <script> tags is a bad thing. WordPress has its own method, called enqueuing, for adding javascript. I pulled my hair out reading the Codex and many tutorials to learn how to get this done. It confused me for a long time. Here is what would have made it much easier for me.

The two things you need to know to properly enqueue javascript in WordPress are:

  1. The function wp_enqueue_script; and
  2. The hook wp_enqueue_scripts

Once I realized that these nearly identical looking things are completely different, it all fell into place.

Here is how both of these fit in my child theme’s function.php file to make it all work.

Line 6 defines the grp_include_scripts function. The sole purpose of this function is to invoke the wp_enqueue_script function which tells WordPress:

  1. to refer to the script by the name “front_page_script”;
  2. the address where the script file is located; and
  3. that the script needs jQuery to run (JQuery is a dependency).

The wp_enqueue_script function says to WordPress, “when it comes time to include script tags in the head of the page being loaded, please add one for my script too. Here is what you need to know about it.”

Like any other php function, grp_include_script() will not execute until called by some other code. That’s where line 12 comes in. The add_action function tells WordPress that you want to do something when it comes to a particular point in its operation. The wp_enqueue_scripts hook is at the point where WordPress determines what scripts need to be loaded with the page being loaded. In line 12, the add_action function tells WordPress, “whenever you reach the wp_enqueue_scripts hook, please run the grp_include_scripts function (line 6) to see what scripts I might have for you.”

And that’s how scripts can be included using function.php without ever touching a template.

Note that I wanted to run this particular script only on the home page, so I used the “if” statement on line 7. Just take out this conditional for scripts that should be loaded on every page.

Posted: Thursday, July 24th, 2014
Category: Wordpress

Leave a Reply