Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
WordPress Plugin Development Cookbook

You're reading from   WordPress Plugin Development Cookbook Explore the complete set of tools to craft powerful plugins that extend the world's most popular CMS

Arrow left icon
Product type Paperback
Published in Mar 2022
Publisher Packt
ISBN-13 9781801810777
Length 420 pages
Edition 3rd Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Yannick Lefebvre Yannick Lefebvre
Author Profile Icon Yannick Lefebvre
Yannick Lefebvre
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Chapter 1: Preparing a Local Development Environment 2. Chapter 2: Plugin Framework Basics FREE CHAPTER 3. Chapter 3: User Settings and Administration Pages 4. Chapter 4: The Power of Custom Post Types 5. Chapter 5: Customizing Post and Page Editors 6. Chapter 6: Extending the Block Editor 7. Chapter 7: Accepting User Content Submissions 8. Chapter 8: Customizing User Data 9. Chapter 9: Leveraging JavaScript, jQuery, and AJAX Scripts 10. Chapter 10: Adding New Widgets to the WordPress Library 11. Chapter 11: Fetching, Caching, and Regularly Updating External Site Data 12. Chapter 12: Enabling Plugin Internationalization 13. Chapter 13: Distributing Your Plugin on WordPress.org 14. Other Books You May Enjoy

Adding output content to page headers using plugin actions

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:

  1. Navigate to the WordPress plugins 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 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', 'ch2pho_page_header_output' );
  6. Add the following code section to provide an implementation for the ch2pho_page_header_output function:
    function ch2pho_page_header_output() { ?>
        <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 }
  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. 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:

Figure 2.2 – Google Analytics code in the page source view

Figure 2.2 – Google Analytics code in the page source view

Note

If you are copying and pasting code from a digital version of this book, you will lose the original code indentation and should correct it in your code editor.

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 registers a function named ch2pho_page_header_output 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. The creation of a configuration panel and user settings 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 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 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, 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. Some of these hooks will be covered in later recipes.

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 recipe, 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:

do_action( 'wp_head' );

See also

  • The Creating a plugin file and header recipe
You have been reading a chapter from
WordPress Plugin Development Cookbook - Third Edition
Published in: Mar 2022
Publisher: Packt
ISBN-13: 9781801810777
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image