
WordPress Plugin Development Cookbook
By :

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.
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.
Follow these steps to add outbound link tracking code to your simple Google Analytics plugin:
ch2-page-header-output
folder in the WordPress plugins
directory of your development installation.ch2-page-header-output.php
file in a code editor.add_filter( 'the_content', 'ch2lfa_link_filter_analytics' );
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; }
add_action( 'wp_footer', 'ch2lfa_footer_analytics_code' );
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 }
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.
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.