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)

Troubleshooting coding errors and printing variable content

As you transcribe code segments from the pages of this book or start writing your own plugins, there is a strong chance that you will have to troubleshoot problems with your code. You might also run into trouble working with data that your plugin is meant to manipulate. This recipe shows basic techniques to identify and quickly resolve these errors while creating a plugin that will hide an item from the navigation menu for users who are not logged in to your site.

How to do it...

Follow these steps to learn how to troubleshoot problematic plugin code:

  1. Navigate to the WordPress plugins directory of your development installation.
  2. Create a new directory called ch2-nav-menu-filter.
  3. Navigate to this directory and create a new text file called ch2-nav-menu-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 - Nav Menu Filter.
  5. Add the following line of code to register a function that will be called when WordPress is preparing data to display the site's navigation menu:
    add_filter( 'wp_nav_menu_objects',
                'ch2nmf_new_nav_menu_items', 10, 2 );
  6. Add the following code section to provide an implementation for the ch2nmf_new_nav_menu_items function. Note that the word functio is mistyped on purpose at the beginning of the first line:
    functio ch2nmf_new_nav_menu_items ( 
                           $sorted_menu_items, $args ) {
        print_r( $sorted_menu_items );
        return $sorted_menu_items;


    If you are using a dedicated code editor, you should be able to tell that the functio text is not a recognized keyword, since it will not be colored as a PHP keyword and might also be underlined to indicate an error.

  7. Save the plugin file and leave your code editor open.
  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. WordPress will display a fatal error message, indicating that the plugin could not be activated, since a parsing error was found. It also indicates the exact filename and line where the error occurred, helping to narrow down where the problem occurred. The actual format of the error message may be different based on the local development tool that you're using:
Figure 2.7 – A fatal error upon plugin activation due to a syntax error

Figure 2.7 – A fatal error upon plugin activation due to a syntax error

  1. Go back to your code editor, correct the spelling of the word function, and save the file.
  2. Activate the plugin a second time. It should now activate correctly.
  3. Back in the code editor, remove the last letter of the word function to re-introduce a syntax error, and save the file.
  4. Visit the development site in your browser. You will now see that the entire site has been replaced with a Parse error message similar to the one we just saw. You may also only get a blank page or a critical error, depending on your web server configuration.
  5. Go to the Appearance section of your development site's Dashboard and Activate a theme other than Twenty Twenty-Two (for example, Twenty Twenty-One or Twenty Twenty). You may need to install one of these themes if they are not present in your development environment.
  6. In the WordPress Dashboard, navigate to the Appearance | Menus item.
  7. If you don't have any menu defined, type Main Menu in the Menu Name field. Check the appropriate Display location checkboxes to assign your new menu to the theme's main navigation area. The exact name of this location will change based on the theme you're using. Click on Create menu to save your menu.
  8. Create an additional item in your menu as a Custom Link, setting the URL to /privatearea and the Link Text to Private Area; then, click on Add to Menu:
Figure 2.8 – Creating a new menu item

Figure 2.8 – Creating a new menu item

  1. Click on the Save Menu button to save your changes.
  2. Back in your code editor, correct the spelling error once again and refresh the page to see the website return to normal. You will also see that a lot of information is now being printed before the navigation menu. This output is generated by the print_r function and is meant to help us understand how the data received by our filter function is organized. Once we have a good understanding of that data, we will be able to properly make changes to this information in the next step. To view the print_r data in a more organized way, bring up the View Page Source function of your browser and search for the keyword Array to quickly find the menu data.
  3. Back in the code editor, replace the line containing the print_r function call with the following code:
    // Check if used is logged in, continue if not logged
    if ( is_user_logged_in() == FALSE ) {
        // Loop through all menu items received
        // Place each item's key in $key variable
        foreach ( $sorted_menu_items as
                  $key => $sorted_menu_item ) {
            // Check if menu item matches search string
            if ( 'Private Area' == 
                    $sorted_menu_item->title ) {
                // Remove item from menu array if found 
                // using item key
                unset( $sorted_menu_items[ $key ] );
  4. Refresh your website, and you will see that the large array printout has disappeared. If you are logged in as the administrator, you will also notice the Private Area link in your menu. Log out of your site or open an incognito session in your browser to see the page without the new menu item.
  5. Go back to the Appearance section and Activate the Twenty Twenty-Two theme.

How it works...

As WordPress assembles a list of all available plugins to display them in the administration interface, it does not check to see whether each plugin's PHP code is valid. This check is only done when a plugin is activated. At that time, any syntax error will be caught immediately and the newly activated plugin will remain inactive, preventing a failure of the entire website.

That being said, once a plugin is activated, its code is evaluated every time WordPress renders a web page, and any subsequent code error that gets saved to the plugin file will cause the site to stop working correctly. For this reason, it is highly recommended to set up a local development environment, as discussed in Chapter 1, Preparing a Local Development Environment, to avoid affecting a live site when an inevitable error creeps up in your plugin code. To avoid potential outages on a live website, it is safer to deactivate plugins before making changes to them and then reactivate them once changes are completed. This way, all changes are validated before the plugin code is reactivated. It should be noted that, with this method, the plugin's functionality won't be available on your site while you make changes, so it is not an optimal way to modify deployed code.

Once the code is working correctly, the second part of this recipe shows us how to visualize the information received by a registered filter function. While the WordPress Codex website provides great documentation of the purpose of most available filters, it does not go into detail about the structure of the information that is sent to each filter function.

Thankfully, the PHP print_r function comes in very handy, since it can display the content of any variable on the screen, no matter what information is stored in the variable that it receives as an argument.

Last, but not least, the implementation of the custom filter function uses the WordPress API is_user_logged_in() function to see whether the person viewing the site has provided login credentials. If the return value of the function is true, our code goes on to parse all the menu items and remove the Private Area menu item.


This is the second time in this chapter that we ask you to activate a theme other than the default WordPress 5.9 Twenty Twenty-Two theme. With WordPress 5.9, WordPress is introducing a new theme-building paradigm where users will be able to modify their site layout using a graphical tool. Some action and filter hooks don't work with this new theme structure in this first version. That being said, all code samples in this book work with the large majority of themes that are available today and are running on most WordPress sites.

There's more...

In addition to the debugging techniques used in this recipe, WordPress offers a number of built-in tools to facilitate plugin troubleshooting.

Built-in WordPress debugging features

While the wp-config.php file, located at the top of the WordPress file structure, is primarily used to store basic site configuration data, it can also be used to trigger a number of debugging features. The first of these is debug mode, which will display all PHP errors, warnings, and notices at the top of site pages. For example, having this option active will show any undefined variables that you try to access in your code along with any deprecated WordPress function. To activate this tool, change the second parameter of the line defining the WP_DEBUG constant from false to true in wp_config.php:

define( 'WP_DEBUG', true );

If the WP_DEBUG line does not appear in your development site's wp-config.php file, you can add it before the line that reads the following:

/* That's all, stop editing! Happy publishing. */

To prevent debug messages from affecting the site's layout, you can download a useful plugin called Debug Bar ( to collect messages and display them in the admin bar, as shown here:

Figure 2.9 – The Debug Bar plugin

Figure 2.9 – The Debug Bar plugin

Other debugging features that can be activated from the wp-config.php file are as follows:

Better debugging with Xdebug

While all of the debugging techniques mentioned in this chapter are valid, they do require manual intervention to insert and remove code, especially in the case of the print_r function called to view data received by the filter function. If you forget to remove a manual debugging statement, your users will end up with debug data on their site if you distribute your work.

As you become more invested in plugin development, you should consider setting up a development server that supports Xdebug. One of the benefits of this debugging tool is that coding errors will be displayed with more details about where they were found and the code that was executed leading up to the error. More importantly, Xdebug allows developers to connect a code editor such as Visual Studio Code to the web server to be able to step through each individual line of code as they are executed. It is also possible to set breakpoints to stop execution in specific places and see data in all variables every step of the way.

See also

  • The Modifying the site generator meta tag using plugin filters recipe