Book Image

WordPress Plugin Development Cookbook - Third Edition

By : Yannick Lefebvre
Book Image

WordPress Plugin Development Cookbook - Third Edition

By: Yannick Lefebvre

Overview of this book

WordPress is one of the most widely used, powerful, and open content management systems (CMSs). Whether you're a site owner trying to find the right extension, a developer who wants to contribute to the community, or a website developer working to fulfill a client's needs, learning how to extend WordPress' capabilities will help you to unleash its full potential. This book will help you become familiar with API functions to create secure plugins with easy-to-use administration interfaces. This third edition contains new recipes and up-to-date code samples, including new chapters on creating custom blocks for the block editor and integrating data from external sources. From one chapter to the next, you’ll learn how to create plugins of varying complexity, ranging from a few lines of code to complex extensions that provide intricate new capabilities. You'll start by using the basic mechanisms provided in WordPress to create plugins, followed by recipes covering how to design administration panels, enhance the post editor with custom fields, store custom data, and even create custom blocks. You'll safely incorporate dynamic elements into web pages using scripting languages, learn how to integrate data from external sources, and build new widgets that users will be able to add to WordPress sidebars and widget areas. By the end of this book, you will be able to create WordPress plugins to perform any task you can imagine.
Table of Contents (15 chapters)

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() { ?>
        i[r].l=1*new Date();
        ga('create', 'UA-0000000-0', 'auto');
        ga('send', 'pageview');
    <?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


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 ( and WordPress Code 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: 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, 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