Adding output content to page headers using plugin actions

php code

php code

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 be able 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 statistics for their site.

How to do it…

  1. Navigate to the WordPress plugin directory of your development installation.
  2. Create a new directory called ch2-page-header-output.
  3. Navigate to this directory and create a new text file called ch2-page-header-output.php.
  4. Open the new file in a code editor and add an appropriate header at the top of the plugin file, naming the plugin Chapter 2 – Page Header Output.
  5. Add a few carriage returns before the ?> characters that close the plugin header section to create space to add the PHP code.
  6. Add the following line of code to register a function that will be called when WordPress renders the page header:
       add_action( 'wp_head', 'ch2pho_page_header_output' );
    Add the following code section to provide an implementation for the ch2pho_page_header_output function:
       function ch2pho_page_header_output() { ?>
         <script type="text/javascript">
    
           var gaJsHost = ( ( "https:" == document.location.protocol ) ?
             "https://ssl." : "http://www." );
    
           document.write( unescape( "%3Cscript src='" + gaJsHost +
             "google-analytics.com/ga.js' \n\
             type='text/javascript'%3E%3C/script%3E" ) );
    
         </script>
         <script type="text/javascript">
    
           try {
            var pageTracker = _gat._getTracker( "UA-xxxxxx-x" );
            pageTracker._trackPageview();
    
           } catch( err ) {}
         </script>
    

    <?php }

  7.  Save and close the plugin file.
  8. Log in to the administration page of your development WordPress installation.
  9. Click on Plugins in the left-hand navigation menu.
  10. Activate your new plugin
  11. 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. The exact name of this function will be slightly different based on which browser you are using. Reading through the page source code, all of the code contained between the two curled brackets of our new function will be visible on 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 recipe, the first line of code that we wrote registered a function named ch2pho_page_header_output with an action hook called wp_head. This action is one among more than 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 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 output for it to function properly. The creation of a configuration panel in Chapter 3, User Settings and Administration Pages will provide a way to configure such information to make our plugins more flexible.

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 that we want our custom function to be associated with. 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 enough to avoid conflicting with functions from other plugins or from the WordPress code. In this recipe, the function name starts with an acronym representing the name of the plugin, 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, has a default value of 1 and should always be set to a number. It should also only be set to a different value for some particular hooks where more than one parameter should be passed to the registered function. Some of these hooks will be covered in later recipes.

One thought on “Adding output content to page headers using plugin actions

Leave a Reply

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