Google Analytics is the defacto standard when it comes to adding analytics to your website. That being said it can be quite difficult to add in WordPress and while there are many plugins to add it, most of them add unneeded promotional notices, take up menu space, and do much more than necessary slowing your website down.

Google Analytics can be added in a number of ways but there is a proper way to add it to your WordPress website that won’t cause your site to break, or slow down. The code I am going to provide will load the script in the footer (which is better for performance) but can be modified to be loaded in the header and I will provide both versions of the script.

Another important details is this code has to be placed in your child theme functions.php OR a site-specific plugin (that you use with your other random functions). You should also only use one version of these plugins and please be sure to add your own tracking ID. In addition this code will load with async to further improve your website load time.

add_action('wp_head', 'add_google_analytics');
function add_google_analytics() { ?>
<!-- Google Analytics -->
<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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
<?php } ?>

This will inject the Google Analytics code into the header of your website if you are looking to load the code into the footer you need to make a slight modification too look like the below code.

add_action('wp_footer', 'add_google_analytics');
function add_google_analytics() { ?>
<!-- Google Analytics -->
<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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
<?php } ?>

Now the code is set to load in the footer, and the best part is this code can be added to your functions.php file and save yourself from using another plugin!

LEAVE A REPLY

Please enter your comment!
Please enter your name here