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)

Modifying the site generator meta tag using plugin filters

Beyond adding functionality or content to a site, the other major task commonly performed by plugins is to augment, modify, or reduce information before it is displayed on the screen. This is done by using WordPress filter hooks, which allow plugins to register a custom function through the WordPress API to be executed when content is prepared before it is sent to the browser.

How to do it...

Follow these steps to implement your first filter callback function that modifies the contents of the generator meta tag found in a site's HTML source code:

  1. Navigate to the WordPress plugins directory of your development installation.
  2. Create a new directory called ch2-generator-filter.
  3. Navigate to this directory and create a new text file called ch2-generator-filter.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 - Generator Filter.
  5. Add the following line of code to register a function that will be called when WordPress is preparing data to output the generator meta tag as part of the page header:
    add_filter( 'the_generator', 'ch2gf_generator_filter', 
                10, 2 );
  6. Add the following code section at the end of the file to provide an implementation for the ch2gf_generator_filter function:
    function ch2gf_generator_filter ( $html, $type ) {
        if ( $type == 'xhtml' ) {
            $html = preg_replace( '("WordPress.*?")',
                '"Yannick Lefebvre"', $html );
        }
        return $html;
    }
  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. Use a web browser to visit your website and display the page source. Searching for the generator keyword will reveal that the content generator meta tag has been modified and now reads as follows:
    <meta name="generator" content="Yannick Lefebvre" />

How it works...

The add_filter function is used to associate a custom plugin function to the second type of WordPress hook, the filter hook. Filter hooks give plugins the chance to augment, modify, delete, or completely replace information while WordPress is executed. To enable this, filter functions are sent data that can be modified as a function parameter. They must return the resulting set of data to WordPress once they have finished making the changes.

Unlike action hooks, filter functions must not output any text or HTML code, since they are executed while output is being prepared, and that would likely result in output showing up in unexpected places in the site layout. Instead, they should return the filtered data.

Taking a closer look at the parameters of the add_filter function, we can see that it is very similar to the add_action function that we saw in the last few recipes:

add_filter( '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 filter data. This function can have any name, with the only condition being that this name must be unique to avoid conflicting with functions from other plugins or from the WordPress code.

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 callback relative to other callbacks that are registered by WordPress itself and by other plugins, with a lower number indicating a higher priority.

The last parameter of the function, accepted_args, has a default value of 1 and indicates how many parameters will be sent to your custom filter function. It should only be set to higher values when you are using filters that will send multiple parameters, as shown in this recipe with the $html and $type arguments.

There's more...

Beyond demonstrating how to change the site generator name, this plugin also showed how to use an advanced PHP function to perform the actual text replacement. We will take a closer look at this function and also explore resources to learn more about filter hooks.

The preg_replace function

The preg_replace function is a PHP function that can be used to perform a search and replace operation within a string based on a search pattern. We use this function rather than the simpler str_replace function, since we want to find and replace both the WordPress keyword and its associated version number, which changes with every version.

Filter hooks online listings and the apply_filters function

Similar to action hooks, information about commonly used filter hooks can be found at the WordPress Codex (https://codex.wordpress.org/Plugin_API/Filter_Reference) or on sites that provide raw function lists (for example, http://hookr.io).

It is also possible to learn about filter hooks by searching for occurrences of the apply_filters function in the WordPress code. As can be seen in the following code, this function has a variable number of arguments, with the first one being the name of the filter hook, the second representing the value that the registered function will be able to modify, and the remaining optional parameters containing additional data that may be useful in the implementation of the filter function:

apply_filters( $tag, $value, [$var] ... );

For the example shown in this recipe, a search for apply_filters( 'the_generator' in the WordPress code reveals that it is called within the the_generator template function:

echo apply_filters( 'the_generator', 
                    get_the_generator( $type ), $type );

See also

  • The Creating a plugin file and header recipe