Using WordPress Footer to Add Custom Javascript

Posted by

In your projects you may need to add custom javascript to a certain post or to all website. We will briefly show how to accomplish this requirement, by using WordPress footer action hook wp_footer.

As the title implies, we prefer to add custom javascript to the footer. Why so? Because a) if you are manipulating HTML elements on the page, you cannot be sure that they are loaded unless you call your scripts after all HTML (except closing of body tags) sent to browser. That is exactly the point where footer is called. b) If you are using some kind of javascript which expects user response, calling your codes earlier than page being loaded may lead to a white background until user response. When your javascript code is in the footer, there is no such a risk.

To add custom javascript to footer, WordPress provides an action hook, namely wp_footer. An action hook should be called prior to its being used. When using hooks, you should also consider if the WP variable is available, if you use one.

Consider the following example where we want to add a script for post ID 3:

This code will not work. Because at ‘init’ level¬†¬†global $post is not yet defined and therefore get_post() will return an empty value. See this diagram which shows sequence of some hooks. global $post is only ready after $wp_query and the earliest hook to use is ‘template_redirect’:

Or actually we may do the post ID check at the footer:

The last one seems more clean, right? In this example, yes, but it is important to know that when we need to communicate with the javascript code about the $post, the earliest point we can achieve that is the ‘template_redirect’ hook. In the next post we will need this information.

 

Leave a Reply

Your email address will not be published. Required fields are marked *