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)

Inserting link tracking code in the page body using plugin filters

After seeing how to append text to existing content, this recipe shows you how to modify page content before it is displayed onscreen. More specifically, the following plugin expands on the Google Analytics header plugin created earlier and adds a JavaScript function to all links that are included in posts and pages to track when they are clicked by visitors.

Getting ready

You should have already followed the Adding output content to page headers using plugin actions recipe to have a starting point for this recipe, and the resulting plugin should be active in your development site. Alternatively, you can download the resulting code (ch2/ch2-page-header-output/ch2-page-header-output.php) for the book's GitHub page.

How to do it...

Follow these steps to add outbound link tracking code to your simple Google Analytics plugin:

  1. Navigate to the ch2-page-header-output folder in the WordPress plugins directory of your development installation.
  2. Open the ch2-page-header-output.php file in a code editor.
  3. Add the following line after the existing code to register a function that will be called when WordPress is preparing data to display a page or post's content:
    add_filter( 'the_content',
                'ch2lfa_link_filter_analytics' );
  4. Add the following code section to provide an implementation for the ch2lfa_link_filter_analytics function:
    function ch2lfa_link_filter_analytics ($the_content) {
        $new_content = str_replace( 'href',
            'onClick="recordOutboundLink( this );return         false;" href',
            $the_content );
        return $new_content;
    }
  5. Add the following line of code to register a function that will be called when WordPress renders the page footer:
    add_action( 'wp_footer',
                'ch2lfa_footer_analytics_code' );
  6. Add the following code section to provide an implementation for the ch2lfa_footer_analytics_code function:
    function ch2lfa_footer_analytics_code() { ?>
        <script type="text/javascript">
            function recordOutboundLink( link ) {
                ga( 'send', 'event', 'Outbound Links',
                    'Click',
                    link.href, {
                        'transport': 'beacon',
                        'hitCallback': function() {
                            document.location = link.href;
                        }
                    } );
            }
    </script>
    <?php }
  7. Save and close the plugin file.
  8. Go to the Posts section of the Dashboard and edit one of the items to add a link within the content, pointing to a location of your choice.
  9. Click Update to save the changes to the modified post.
  10. In your web browser, refresh your website to see the modified post.
  11. Right-click on the new link and Inspect it using your browser's developer tools:
Figure 2.6 – Custom JavaScript code added to web links in the page output

Figure 2.6 – Custom JavaScript code added to web links in the page output

As seen in Figure 2.6, the link tag now has an additional onClick JavaScript property with code that will be called when visitors follow it, along with the definition of the recordOutboundLink function in the page footer.

How it works...

The content filter function that is put in place by calling add_filter receives the entire content of all the posts and pages before they are rendered to the browser and is allowed to make any number of changes to this information. In this case, we are using the PHP str_replace function to search for any occurrence of the href string, which indicates a link. When the string is found, it is replaced with a call to a JavaScript function while preserving the original href tag.

To make this plugin complete, it also needs to provide an implementation for the JavaScript recordOutboundLink function. This is done by registering a custom function with the wp_footer action hook, which will output extra content once in the website's footer.

The resulting plugin automates many of the tasks related to tracking usage data on a website using Google Analytics.

See also

  • The Adding output content to page headers using plugin actions recipe
  • The Adding text after each item's content using plugin filters recipe