Google analytics is a functionality that you will need on almost all of the websites you create. It allows you to track all sorts of data about the visitors of your website. You can see the most popular pages, time on site, bounce rate of your site and how the visitor found your site.
In this tutorial we are going to see how you will add this to your WordPress site.
There are a few different solutions you can go with to add Google Analytics code to your website.
- Install a WordPress plugin to add Google Analytics to your page
- Write a WordPress plugin to add Google Analytics to your page
As there are multiple different ways of doing this which is the best way?
Write Code In Functions.php
You can write PHP code into your functions.php file so that it will add your Google Analytics code into the footer of your theme by using the wp_footer action. Using this method means you could code something to be able to change the Google Analytics code in the future. But you don't really change the code enough times to grant doing this, also you have the same problem as above in that if you change your WordPress theme you have lost your Google Analytics code.
Download A WordPress Plugin
The next option is to use a WordPress plugin to add the Google Analytics code into the header or footer of your theme. In theory this is the best solution to this problem as your Google analytics code will still be added if you change your theme.
The reason why this could be a bad solution is because you are using another developers plugin so you can not be sure exactly how their plugin works and if any additional code is being ran that isn't needed.
Create A WordPress Plugin
The best solution for this problem will be to create your own WordPress plugin to add the Google analytics code to the header or footer of your WordPress theme.
Creating your own plugin you will have full control over if you have your code inserted into the head tag or the footer of your theme.
To create you own plugin to add Google Analyics, first create a new WordPress plugin. Add a folder into your wp-content/plugins and add a new php filer with the following code.
Extended Google Analytics for WordPress
- Add’s google analytics code
- Auto link adsense to analytics
- Auto event tracking for downloads, mailto and outbound links
- Select which file extensions to download track
- Tool to generate campaign tracking links to use in newsletters and other campaigns