Customizing Google Analytics Configuration in the Site Kit Plugin

The Site Kit plugin by Google makes it trivial to integrate your WordPress site with various publisher-facing Google services such as Google Analytics. In addition to exposing key insights from these services directly in your WordPress dashboard, it also automatically places the necessary code snippets on your page to ensure these metrics can be gathered properly.

In this post we will look at Google Analytics specifically and how you can customize its behavior in the Site Kit plugin. While the default configuration already gives you access to many valuable metrics, Google Analytics becomes really powerful when you have tailored it to your specific use-cases. With Site Kit currently still in Beta, the user-facing configuration options for Google Analytics are minimal. While we are exploring how we can expose more customization opportunities through the plugin’s settings UI, it may be a while until these improvements are included in a new plugin’s release. Since its beta 1.0.4 release though, the plugin includes filters to modify the Google Analytics configuration, so as a developer you can tweak it in almost any way you like already today.

Site Kit and AMP

The Site Kit plugin is fully AMP compatible, so Google Analytics works in AMP context (via the AMP plugin) as well as in non-AMP context. If you are looking into how to customize the configuration though, it is crucial to know that the Google Analytics tracking code is integrated a little bit differently between AMP and non-AMP.

Of course, if you intend to only customize Google Analytics behavior specifically for your own website, you’re free to only implement one of the two ways, depending on whether your website uses the AMP framework or not. If you intend to build a solution that you would like to publish and share with other WordPress and Site Kit users, I strongly recommend to cover both scenarios. At least having a basic understanding of the two alternatives will be helpful in either way, so we’ll look at both non-AMP and AMP in this post.

For non-AMP, Site Kit places the recommended gtag.js snippet in your site, which loads the necessary scripts and defines a base configuration.

For AMP, Site Kit adds an instance of the amp-analytics custom element to your site, configured to use gtag.js under the hood as well. The amp-analytics component is AMP’s interface to various analytics providers, and it ensures these are integrated in a more performant way by directly communicating to the analytics providers’ servers. In case you have configured multiple analytics providers for your site, the amp-analytics component aggregates events from the page only once and batches requests to the analytics providers, instead of doing it individually for every provider.

Because the integration of Google Analytics in non-AMP vs AMP happens in a different way, one via a JavaScript snippet and the other via a custom element, the configuration happens a bit differently as well.

For non-AMP, the Site Kit plugin fires a googlesitekit_gtag_opt filter to modify the configuration object (in PHP it is an associative array) that is used in the gtag( 'config', ... ) call in the JavaScript snippet. See the non-AMP filter in the plugin’s source code here.

For AMP, the plugin fires a googlesitekit_amp_gtag_opt filter to modify the configuration object (associative array in PHP) that is included as JSON in the amp-analytics custom element. See the AMP filter in the plugin’s source code here.

The two variants generally support the same parameters, but they need to be specified in the configuration object in different places. I recommend reviewing the gtag.js reference and the amp-analytics reference respectively. We’ll look closer into a few particular differences with two more specific examples outlined below.

Anonymizing IP Addresses

A commonly required tweak to the default Google Analytics configuration is to anonymize IP addresses that are sent to Google servers through the tracking code. This improves user privacy by making the last identifying bits in the IP address unrecognizable. Accomplishing this with Google Site Kit is straightforward.

For non-AMP, you need to use the googlesitekit_gtag_opt filter and simply set the anonymize_ip configuration option, as shown below:

add_filter(
	'googlesitekit_gtag_opt',
	function( array $options ) {
		// See https://developers.google.com/analytics/devguides/collection/gtagjs/ip-anonymization.
		$options['anonymize_ip'] = true;
		return $options;
	}
);Code language: PHP (php)

For AMP, you actually don’t need to do anything. The amp-analytics component sets this parameter and thus enforces this privacy improvement by default.

Tracking Custom Events

Let’s look at our second example. As mentioned, Google Analytics only becomes really powerful once you start tailoring it to your site’s specific goals. This typically involves defining certain events that you want to track whenever a user performs them.

For the sake of this tutorial, we’ll use a very simple event: We’ll track when a user submits a WordPress comment on your site. Obviously this is quite basic, but it should give you an idea how to add event tracking for more complex events too.

Generally, for tracking an event with Google Analytics, we need to determine when that specific event occurs (for example by listening to a DOM event), and then we need to inform Google Analytics that the event has happened, including some optional details we can define and provide. In our example, this would mean the following:

  1. We listen to when someone hits the submit button in the WordPress comment form (i.e. we listen to the click DOM event on the #commentform input[type="submit"] element).
  2. We send a Google Analytics event with name submit_comment (an arbitrary name defined by us), and an associated event category of engagement (this is also arbitrary, but the specific case of “engagement” is one of the default categories Google Analytics supports and uses).

That’s all there is to it. Now let’s look at the implementation.

For non-AMP, we need to add a custom JavaScript snippet that takes care of the above two steps. We can hook it into the wp_enqueue_scripts action at a relatively late priority (e.g. 99). In the hook callback, we should check whether the gtag.js script from Site Kit (which uses a handle of google_gtagjs) is enqueued before proceeding, so that we don’t unnecessarily add our inline JavaScript snippet. We’ll use the wp_add_inline_script() function, which by default will add the script output right after enqueuing the original script file (in our case gtag.js). Our inline script itself is fairly straightforward if you’re familiar with JavaScript: We check for existence of the comment form’s submit button in the current page, and then listen to the click DOM event on it. Once it’s fires, we call the gtag() function to pass the Google Analytics event described before. Here is what the whole code would look like:

add_action(
	'wp_enqueue_scripts',
	function() {
		if ( ! wp_script_is( 'google_gtagjs' ) ) {
			return;
		}
		// See https://developers.google.com/analytics/devguides/collection/gtagjs/events#send_events.
		ob_start();
		?>
		<script>
	document.addEventListener( 'DOMContentLoaded', function() {
		var submitButton = document.querySelector( '#commentform input[type="submit"]' );
		if ( submitButton ) {
			submitButton.addEventListener( 'click', function() {
				gtag( 'event', 'submit_comment', { 'event_category': 'engagement' } );
			} );
		}
	} );
</script>
		<?php
		$script = substr( trim( ob_get_clean() ), strlen( '<script>' ), - strlen( '</script>' ) );
		wp_add_inline_script( 'google_gtagjs', $script );
	},
	99
);Code language: JavaScript (javascript)

For AMP, it’s a bit easier as we don’t need to fiddle with custom JavaScript at all: Instead, we use the aforementioned googlesitekit_amp_gtag_opt filter, as the amp-analytics component allows to specify event triggers right as part of the analytics provider configuration, in a triggers property. Every event trigger in this property needs a unique slug for which we’ll choose comment_submission. Then, we can simply define the element we would like to listen for an event on (via a selector property), which event specifically we would like to listen for (via an on property), and information about which Google Analytics event we would like to send (via a vars property). Here is the full resulting code for AMP:

add_filter(
	'googlesitekit_amp_gtag_opt',
	function( array $options ) {
		if ( ! isset( $options['triggers'] ) ) {
			$options['triggers'] = array();
		}
		// See https://developers.google.com/analytics/devguides/collection/amp-analytics/#measure_events
		// and https://amp.dev/documentation/components/amp-analytics/#triggers.
		$options['triggers']['comment_submission'] = array(
			'selector' => '#commentform input[type="submit"]',
			'on'       => 'click',
			'vars'     => array(
				'event_name'     => 'submit_comment',
				'event_category' => 'engagement',
			),
		);
		return $options;
	}
);Code language: PHP (php)

And that’s it already for this brief tutorial. I hope it gives you a basic understanding on how to tailor Google Analytics behavior of the Site Kit plugin to your needs.

In case you want to look at the example code as a whole, or actually use it as is on your site, I have prepared two mini plugins via GitHub Gists:

Note that, if you wanna use them, they require PHP 7+ to work. I hope they provide a good starting point for you to come up with much more comprehensive setups that help you gather insights about your website specifically.


Posted

in

,

by

Comments

2 responses to “Customizing Google Analytics Configuration in the Site Kit Plugin”

  1. Raul Rodriguez Avatar
    Raul Rodriguez

    Just for the benefit of novice users, please mention where to add the snippets (function.php)

  2. Jörg Halitschke Avatar
    Jörg Halitschke

    Hi Felix

    I’ve tried your amp filter 1:1 but nothing happens to the amp-analytics using WP 5.6.1.
    I want to adapt this for the dataLayer vars (as you discussed on Github).

Leave a Reply

Your email address will not be published. Required fields are marked *