There’s a number of different ways you can install Google Analytics on your WordPress site. There is a way to install it in the functions.php file using an action hook. Action hooks allow you to insert code in specific sections of your website.
Note: The best way to add Google Analytics to your website is to use a plugin such as: Google Analytics by Yoast. By keeping your analytics code in a plugin, you do not run the risk of losing data if you ever have to switch your site’s theme in the future. This article is more of a reference on the practicality of hooks and how they work.
It is recommended to add your tracking code right before the closing </head> tag on your website. For this reason you should use the wp_head action hook. If your theme was coded properly, the wp_head occurs right where Google recommends you place it.
Create a file containing the tracking code.
In order to find your tracking code, login to your Google Analytics account, and select the Admin tab. Select Tracking Info and then Tracking Code. Create a new file in your theme’s directory and label it analyticstracking.php. Paste the tracking code into this file and save it.
Create a function which includes the file containing the tracking code.
You will want to place this function into your functions.php file.
function google_analytics() { include_once("analyticstracking.php"); }
Hook the function into the wp_head action.
Similarly, this code also goes in your functions.php file.
add_action('wp_head', 'google_analytics');
If this method is confusing or you would like to take a different approach, there are a number of plugins that achieve the same result. A simple search for Google Analytics in the plugins section of WordPress will give you a plethora of options to choose from.
Sam says
Thanx man, You’ve saved my time 🙂