WordPress – Building a Google Analytics plugin

If you just want to see the final plugin, it is available on GitHub


Google Analytics is a good way to track who is interacting with your site, and can provide some helpful insights. It is also easy to set up basic analytics, with the tracking code Google supplies. There are two ways you can insert this into your site:

  1. By copying the tracking code into your themes footer.php file
  2. By using a WordPress plugin to automatically enter the code into each page

Using a plugin is by far the superior option, as you can then change the theme and rest assured your tracking will continue to work. You can also re-use the plugin on each new WordPress install you create. A number of plugins already exist on the WordPress plugin directory, but I will show you how to build your own, which is a good learning experience and will be free from the bloat which some of the existing plugins contain.

Creating the plugin

The first step to creating a plugin is to add the necessary files, so that it is recognized by WordPress and can be installed from the admin menu. We will start by creating a new file for our files – create a folder called ‘analytics’ in wp-content\plugins. The name of the folder will be the name of our plugin.
Next create a file called analytics.php in the root of this new folder. The folder name and file name must be the same. At the top of this file paste the following code.

<?php
/**
 * Plugin Name: Analytics
 * Description: Simple Google Analytics implementation
 * Version: 1.0
 * Author: Bradley Taylor
 */
	

The comment shows WordPress details about the plugin. Any code after this comment gets run whenever your page loads. By using the concept of hooks and filters, we can alter the output of our theme’s pages. We will use the wp_footer hook to add the tracking code to the end of each page.
First create a new file (‘script.php’) that contains the tracking code. Line 7 should be updated to use your URL and tracking code.

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-xxxxxxxx-x', 'example.com');
  ga('send', 'pageview');

</script>
	

Next add the following to our original analytics.php file. The code simply include the tracking code every time wp_footer is called. The wp_footer function should be included in every theme.

function  load_analytics(){
	include 'script.php';
}
 
add_action ('wp_footer', 'load_analytics');
	

Adding Options

At this stage the plugin works, and your tracking code should be included at the bottom of each page (as long as it has been enabled in wp-admin). However, if we decide to use the plugin on a different site their is no easy way to change the tracking code. We can change this by adding a settings page in the admin menu. Firstly lets create the settings page. Create a new file – settings.php, which will contain our form:

<div class="wrap">
	<h2>Analytics Settings</h2>
	<form method="post" action="options.php">
		<?php
		settings_fields( 'analytics-options' ); 
		do_settings_sections( 'analytics-options', 'analytics-main' );
		submit_button(); 
		?>
	</form>
</div>
	

As you can see the form is going to be outputted by the system. The wrap class styles the page like all the default WordPress admin pages.

The next step is to register our admin page so that it appears in the settings menu. Once again we use hooks for this.

//Register Admin Page
function analytics_menu() {
	add_options_page('analytics', 'Analytics', 'manage_options', 'analytics-options', 'analytics_options' );
}
//draw the settings page
function analytics_options() {
	if ( !current_user_can( 'manage_options' ) )  {
		wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
	}
	include 'settings.php';
}
//register the option
add_action('admin_menu', 'analytics_menu' );
	

The main bit of code here is the add_options_code function. The 5 arguments are as follows:

  1. The text displayed in the page title
  2. The text displayed in the menu
  3. The permissions level the user must have, in order to view and access the menu item
  4. A unique slug for the page. (This is used for the URL)
  5. The function called to output the page

The analytics_options function is used to output the page. It simply inputs the page we created a minute ago, if the user has the correct permissions. However, the page will not show anything yet, as the forms have not been configured. This required the most significant chunk of code so far. This should once again go in the main analytics.php file.

//register settings
function register_settings() { 
	register_setting( 'analytics-options', 'analytics-options' );
	add_settings_section( 'analytics-main', 'Analytics Main', 'draw_analytics_main', 'analytics-options' );
	add_settings_field( 'tracking-id', 'Enter Your Tracking Id', 'draw_tracking_id', 'analytics-options', 'analytics-main', array('label_for' => 'tracking-id') );
	add_settings_field( 'domain-id', 'Enter Your Domain', 'draw_domain_id', 'analytics-options', 'analytics-main', array('label_for' => 'domain-id') );
}
//draw the settings
function draw_analytics_main(){
	echo 'Please enter your data from when you signed up to Google analytics';
}
//draw the input for the tracking-id
function draw_tracking_id(){
	$value = get_option( "analytics-options", "" );
	if (is_array($value)){
		$value = $value['tracking-id'];
	}
	echo '<input type="text" name="analytics-options[tracking-id]" id="tracking-id" value="'.$value.'"></input>';
}
//draw the input for the domain-id
function draw_domain_id(){
	$value = get_option( "analytics-options", "" );
	if (is_array($value)){
		$value = $value['domain-id'];
	}
	echo '<input type="text" name="analytics-options[domain-id]" id="domain-id" value="'.$value.'"></input>';
}
//register the settings
add_action('admin_init', 'register_settings' );
	

The main concept here is another action, which gets called when any admin page loads, and configures the settings. We start of here by registering the option, which will be stored in the database. We do this with the register-setting function, to which we pass the options name.
The next thing we do is create a section with add_settings_section. Each admin page is made up of a number of sections. Each section can contain any number of input fields. It also starts with some descriptive text, which in this case is outputted with draw_analytics_main. The fields themselves are outputted using add_settings_field, and a secondary callback function. The current value is entered into the fields, so that it is clear to the user that the current value is properly saved. The name of the inputs is same as the option in the database. This means that WordPress will automatically deal with saving the values.

At this stage their is just one step left – to modify the tracking code so that our options are entered:

$value = get_option( "analytics-options", "" );
if (is_array($value)){
	$tracking = $value['tracking-id'];
	$domain = $value['domain-id'];
	?>
<script>
	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

	ga('create', '<?php echo $tracking; ?>', '<?php echo $domain; ?>');
	ga('send', 'pageview');
</script>
	<?php
}

We first check that the values have been set, and then enter them into the appropriate part of the tracking code. The proper code will then be included as expect.

That draws to a close this guide to creating a Google Analytics plugin. Thank you for reading.
The final plugin is avaliable on GitHub