Google Analytics
A lightweight WordPress plugin to add Google's global site tag (gtag.js) to your site, the modern way., (*1)
The modern way? The script is added with support for preloading, which will provide a small performance boost on modern browsers.
Modern browsers are those that support the async script attribute. This does not include IE 9 and older mobile browsers., (*2)
You can use this plugin with Universal Analytics or Google Analytics 4 properties or, to help ease the transition period, dual tagging is also supported., (*3)
Beside that, the plugin doesn't do more. No fancy report view in your admin, no authentication requirements, no additional scripts, and no ads for random blog posts., (*4)
Installation
Install via Composer, (*5)
$ composer require wearerequired/required-google-analytics
Add you property ID at Settings > Reading > Google Analytics., (*6)
Disable Analytics for opted-out users
The plugin provides a function to let users opt out of Google Analytics measurement. If the function window.requiredGADoOptOut() is called a ga-opted-out item is stored in the local browser storage and the window property window['ga-disable-PROPERTY_ID'] will be set to true., (*7)
Example:, (*8)
<a href="#" onclick="requiredGADoOptOut();return false">Opt-out from Google Analytics for this site.</a>
Event Tracking for Universal Analytics
The plugin provides a small layer that transform data attributes on an HTML element to a Google Analytics event. To enable the layer use the following filter:, (*9)
add_filter( 'required_ga.enable_event_tracking', '__return_true' );
To track the click event of a button you can now use the following data attributes:, (*10)
-
data-ga-event-action: Event action.
-
data-ga-event-on: Optional. Event trigger. Defaults to click and can be any DOM event.
-
data-ga-event-category: Optional. Event category.
-
data-ga-event-label: Optional. Event label.
-
data-ga-event-value: Optional. Event value.
Example usage:, (*11)
<button data-ga-event-action="xyz">Click me!</button>
<button data-ga-event-action="play_video" data-ga-event-category="engagement">Click me!</button>
Additional Config Info
To configure custom dimensions and metrics you can use the required_ga.additional_config_info filter. By default the forceSSL and anonymizeIp fields are set to true., (*12)
Example usage:, (*13)
add_filter( 'required_ga.enable_event_tracking', function( $config ) {
$config['custom_map'] = [
'dimension1' => 'author',
];
if ( is_singular( 'post' ) ) {
$config['author'] = get_the_author_meta( 'display_name', get_post()->post_author )
}
return $config;
} );
Support for analytics.js (Universal Analytics)
Starting with version 2.0 the plugin enqueues gtag.js. If you need support for analytics.js you can continue using the 1.x branch., (*14)
$ composer require wearerequired/required-google-analytics:"^1.0"