Adding Google Analytics Event tracking to WordPress buttons

Normally, to track button clicks as Google Analytics (GA) events, you simply add an ‘onclick’ attribute against the button or anchor (link) tag:

<button type="submit" onclick="ga('send', 'event', 'click', 'button', 'Contact Form');">Submit</button>

When it’s not possible to add this code to buttons directly, e.g. when the buttons are built dynamically, sometimes you need to add the code to the buttons programmatically. To do this:

1. Create a javascript file with the jQuery required to add the onclick tag

The code below adds an event to track clicks on buttons or links that refer to the homepage contact form (#hpcontactform):

(function($) { $(document).ready(function() { jQuery('#hp_contact_form button').click(function() {
__gaTracker('send', 'event', 'button', 'click', 'hp ' + jQuery(this).text());
}); jQuery('a[href$="#hp_contact_form"]').click(function() {
__gaTracker('send', 'event', 'button', 'click', jQuery(this).text());
}); }) })(jQuery);

NOTE: WordPress uses jQuery in a ‘safe mode’ to prevent conflicts, so using the standard $ notation will not work.

2. Save the code in your WP theme’s js directory

NOTE: Save this code in your child theme’s js directory if you’re using a child theme

3. Call the javascript from functions.php

Add the following to your functions.php to call the jQuery:

function add_event_tags() { // register your script location, dependencies and version wp\_register\_script('add_events',
get\_stylesheet\_directory\_uri() . '/js/add_events.js',
'1.0' );
// enqueue the script if this is the right page if (is_page (2) ) { // can use page Id, title or slug here
} } add_action('wp_enqueue_scripts', 'add_event_tags');

You can apply this code to a single page by making the wpenqueuescript() function conditional on the page slug:

if(is_page('page-slug-here')){ wp_enqueue_script('add_events'); }

NOTE: In WP v4.5.3 I had to add this to the parent theme’s functions.php – it wouldn’t work if I added this to the child theme’s functions.php

4. Reload the page and test

Open GA and watch Real Time Events, then click one of the links.

Paul Middleton

Read more posts by this author.

Illawarra, NSW
comments powered by Disqus

Subscribe to Funnel Vision

Get the latest posts delivered right to your inbox.

* indicates required