How to use hooks and add output content to page head
A common action performed by plugins is to add extra content to the header of visitor-facing pages generated by WordPress. This recipe shows you how to register an action hook function to add such additional content. To make this example more concrete, we will use the Google Analytics page header JavaScript code that so many people use to get good page view analytics for their site.
How to do it
Follow these steps to learn how to register custom code to add content to a site’s page headers:
Example 1:
- Navigate to the WordPress plugins directory of your development installation.
- Create a new directory called
google-analytics-js-code
- Navigate to this directory and create a new text file called
v-google-analytics_code.php
- Open the new file in a code editor and add an appropriate header at the top of the plugin file.
/* Plugin Name: Google Analytics Code Plugin URI: Description: Functionality to add Google Analytics code to <head> tag in the frontend Version: 1.0 Author: Vinay Vengala Author URI: https://www.vengalavinay.com/contact-us/ License: GPLv2 */
- Add the following line of code at the end of the file to register a function that will be called when WordPress renders the page header:
add_action( 'wp_head', 'v_add_google_analytics_code' );
- Add the following code section to provide an implementation for the
v_add_google_analytics_code
function:function v_add_google_analytics_code() { ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r; i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)}, i[r].l=1*new Date(); a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g; m.parentNode.insertBefore(a,m)}) (window,document,'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-0000000-0', 'auto'); ga('send', 'pageview'); </script> <?php }
- Save and close the plugin file.
- Log in to the administration page of your development WordPress installation.
- Click on Plugins in the left-hand navigation menu.
- Activate your new plugin.
- Navigate to your website’s front page and use your browser’s View Page Source function to see the HTML source code for the site. Note that the exact name of this browser function will be slightly different based on which browser you are using. Search for UA-0000000-0 to see that all of the code contained between the two curled brackets of your new function is in your website’s header:
Example 2:
- Navigate to the WordPress plugins directory of your development installation.
- Create a new directory called
google-adsense-script
- Navigate to this directory and create a new text file called
v-google-adsense_code.php
- Open the new file in a code editor and add an appropriate header at the top of the plugin file.
/* Plugin Name: Google Adsense Code Plugin URI: Description: Functionality to add Google Adsense code to <head> tag in the frontend Version: 1.0 Author: Vinay Vengala Author URI: https://www.vengalavinay.com/contact-us/ License: GPLv2 */
- Add the following line of code at the end of the file to register a function that will be called when WordPress renders the page header:
add_action( 'wp_head', 'v_add_google_adsense_code' );
- Add the following code section to provide an implementation for the
v_add_google_adsense_code
function:function v_add_google_adsense_code() { ?> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-0000000000000000" crossorigin="anonymous"> </script> <?php }
- Save and close the plugin file.
- Log in to the administration page of your development WordPress installation.
- Click on Plugins in the left-hand navigation menu.
- Activate your new plugin.
- Navigate to your website’s front page and use your browser’s View Page Source function to see the HTML source code for the site. Note that the exact name of this browser function will be slightly different based on which browser you are using. Search for 0000000000000000 to see that all of the code contained between the two curled brackets of your new function is in your website’s header:
How it works…
The add_action
function is used to associate custom plugin code to one of the two types of WordPress hooks, the action hook. As mentioned briefly in this chapter’s introduction, hooks are the enabling functionality that make plugins possible in WordPress. Action hooks enable the execution of additional code at specific points when either public-facing or administration pages are prepared to be displayed. This code usually adds content to a site or changes the way a given action is performed.
In this, the first line of code that we wrote registers a function named v_add_google_analytics_code
with an action hook called wp_head
. This action is one among more than 2,500 action hooks that are available in current versions of WordPress, and it allows any registered function to output additional content to the page header. Since all echoed content will be displayed, we can write our callback function very simply by placing ?>
and <?php
tags around the Google Analytics code. This will tell PHP to display all the content that is within that function’s body, as opposed to interpreting it.
As you may have noticed, the current code is not very flexible, since you would need to hardcode your Google Analytics account number in the plugin code for it to function properly.
Now, to fully understand its syntax, let’s take a closer look at the complete add_action
function:
add_action( 'hook_name', 'your_function_name', [priority], [accepted_args] );
The first parameter, the hook name, indicates the name of the WordPress hook with which we want our custom function to be associated. This name must be accurately spelled; otherwise, our function will not be called and no error message will be displayed.
The second parameter is the name of the plugin function that will be called to perform an action. This function can have any name, with the only condition being that this name must be unique to avoid conflicts with function names from other plugins or from the core WordPress code. In this, the function name starts with an prefix, making it much more unique.
The priority parameter is optional
, as indicated by the square brackets, and has a default value of 10
. It indicates the execution priority of this plugin relative to other plugin functions that hook into the same action, with a lower number indicating a higher priority. Any plugin can register one or more functions with an action hook using the add_action
function. As it is rendering web pages, WordPress keeps a queue of all entries and calls them at the appropriate moment. It is interesting to note that the hook mechanism is also used by WordPress itself, as it regularly calls the add_action
function in its own code to register functions to be called at the right time. If you realize that you need your function to be called before or after other plugins that are registering with the same hook, change the value of the priority parameter.
The last parameter of the add_action
function, accepted_args, is also optional, has a default value of 1
, and should be assigned a number when set. It should only be set to a different value for some particular hooks where more than one parameter will be passed to the registered function.
There’s more…
Finding the right hooks to register plugin functions is a large part of WordPress plugin development. Fortunately, there are a number of ways to get information on existing hooks and to learn when they get called during the WordPress page generation process.
Action hooks online listings
The WordPress Codex (https://codex.wordpress.org/) and WordPress Code Reference (https://developer.wordpress.org/reference/) are documentation sites that contain a multitude of information that is useful to users and developers alike. When it comes to action hooks, the Codex contains information on the most commonly used hooks, with basic descriptions indicating how they can be used; it can be found here: https://codex.wordpress.org/Plugin_API/Action_Reference. However, this is not a complete listing.
There are many third-party sites that parse the WordPress source code and provide their own hook listings (for example, http://hookr.io). While hooks are not as eloquently documented in these types of raw listings, they do provide basic information on their names and where they are called, as WordPress generates pages for visitors and administrators. These details can often be enough to find a hook based on the functionality that you are trying to implement.
Searching for hooks in the WordPress source code
Since WordPress is open source, another way to find information about hooks is to search directly within its code. For every action hook that accepts user functions, you will see a call to the do_action
function to execute all the registered items. As you can see, the function takes two or more arguments, with the second one(s) being optional:
do_action( 'tag', [$arg] );
For the example shown in this, a search for do_action( 'wp_head' )
reveals that it is the only function that is called when a WordPress theme makes a call to the wp_head()
function in its header file:
Leave a Reply
You must be logged in to post a comment.