Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying WordPress Plugin Development Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
WordPress Plugin Development Cookbook

WordPress Plugin Development Cookbook - Second Edition

By : Yannick Lefebvre
4.4 (12)
close
close
WordPress Plugin Development Cookbook

WordPress Plugin Development Cookbook

4.4 (12)
By: Yannick Lefebvre

Overview of this book

WordPress is a popular, powerful, and open Content Management System. Learning how to extend its capabilities allows you to unleash its full potential, whether you're an administrator trying to find the right extension, a developer with a great idea to enhance the platform for the community, or a website developer working to fulfill a client's needs. This book shows readers how to navigate WordPress' vast set of API functions to create high-quality plugins with easy-to-configure administration interfaces. With new recipes and materials updated for the latest versions of WordPress 4.x, this second edition teaches you 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 and execute custom user code. You will then see how to design administration panels, enhance the post editor with custom fields, store custom data, and modify site behavior based on the value of custom fields. You'll safely incorporate dynamic elements on web pages using scripting languages, 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 (13 chapters)
close
close

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
Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
WordPress Plugin Development Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon