WordPress – Google Analytics (ga) tracking code as a plugin

For wordpress sites I build, I insert the google analytics (ga) tracking code into the html head section via a plugin. The code for this is shown below. Alternatively, it is relatively easy to slip the tracking code directly into the ‘header(s)’ template (Located:\wp-content\themes\active-theme\header.php) as described by google analytics on the ‘tracking-code’ page. However, I prefer the ‘cleaner’ approach of separating the code into a separate file. So much easier to read if it is ever required…

I also use the WordPress function ‘is_user_logged_in’ to remove most of my visits to the site as I am typically signed in to my WP admin account.

Here is the code:

	Plugin Name: Site-Name Google Analytics Plugin
	Plugin URI: http://--relevant url?
	Description: Adds the Google analytics tracking code to ... Site-Name
	Author: Author name
	Version: 1.0
	Do not insert tracking code if the user is logged in (ie internal traffic) 
	This is wrapped in a function (insert_ga_tracking() ) so it can 
	be loaded with the 'init' hook. An error can be produced otherwise...

	function insert_ga_tracking()
		if ( ! is_user_logged_in() )
			add_action( 'wp_head', 'Site-Name_google_analytics', 10 ); 
			function Site-Name_google_analytics() 
				<!-- Global site tag (gtag.js) - Google Analytics -->
				<script async src="">
				  window.dataLayer = window.dataLayer || [];
				  function gtag(){dataLayer.push(arguments);}
				  gtag('js', new Date());

				  gtag('config', 'UA-12345678-1');

	add_action('init', 'insert_ga_tracking');

To use this code…

Create a php file in the folder location: Site-Name/wp-content/plugins/ and add the script above to this file.

The tracking code between the double quotation marks on line 25 needs the tracking code supplied by google for your site (located in the admin/tracking for your google analytics property).
‘Site-Name’ in the code above can be changed to the target site or removed (in all four locations…). I add the site name as a check to ensure the right tracking code goes to the right site location.

Then, in the WP Admin dashboard, go to ‘installed plugins’ and activate the plugin which should be displayed with the name you specified ‘Plugin name’.

That should be all there is to it but don’t forget to test it using google analytic’s testing feature.

Leave a Reply

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