In this article, I will explain how to add Google Analytics via functions.php. It’s pretty easy to do, but it’s recommended to use a child theme to make changes, otherwise all custom code may be lost when the theme is updated. Hopefully creating a child topic won’t cause any problems. If you need to add Metrics, the details are here: https://workinnet.ru/metrika-and-analytics-functions/
By the way, a better way is to put the custom code in a separate plugin. This will make it theme-independent, as well as more easily testable and transferable to other sites.
Installing Google Analytics via functions.php
So, first of all, create a counter on the official site Google Analytics, I’m sure this action will not cause you any problems. Once the counter is generated, a code will be provided, which will be needed later for integration.
If you don’t know where to look, here’s a hint (relevant for the new version):
- Going into Analytics.
- Select your account.
- The following route: Administrator → Resource tab → Tracking → Tracking Code.
There you will find the code you need.
Connection code
So, now the easiest part is connecting Google Analytics. The code will look like this:
add_action('wp_head', 'wp_analyticass');
function wp_analyticass() {
?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-128894643-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-123456789-1');
</script>
<?php }
I’ll decipher it.
The first two lines are responsible for generating the function and binding it to a specific hook. In fact, we place analytics in the header. If there is a desire to send it to the footer, “wp_head“ should be replaced with “wp_footer“. But then the accuracy of data collection may drop.
Everything in between – Global site tag (gtag.js) – Google Analytics – and
<?php }
and there’s a counter code. You’ll have your own.
That’s it, the code has been posted. Save the functions.php file, clear the site cache, if the appropriate plugins are installed, enjoy.
Possible problems
Some plugins that minify and merge JS can create some problems. Custom code and other methods that trigger asynchronous or delayed script loading can also disrupt analytics.
But hopefully we won’t run into any problems. Have a successful attendance analysis and until we meet again ?