There is often a need to analyze the site, check visits, monitor user factors. This is necessary to improve the website, better understand its design and SEO. In the case of WordPress, there are almost no problems with connecting Yandex Metrics or Google Analytics. You can install plugins that will automatically add what you need, you can just put the code in the right file. I personally prefer to put the custom code in a separate plugin, but today I’ll tell you how to do it through a function file.
P. S. A much more efficient and correct way is to put the code in a separate plugin. It will not affect the performance of the site in any way, it will allow you to work more conveniently, and besides, your code will not depend on the theme. Everything that is not directly tied to the theme, it is better to bring in a plugin. And this task is far from hard, but for now you can limit yourself to what I have told here.
Add Metrics or Google Anaytics to functions.php
Let’s first understand where to get the counters. This task is simple, it only requires you to register and get the code. I will not describe how to do this. The description is in the help on the official sites: https://metrika.yandex.ru/ и https://analytics.google.com/ In general, getting the code will not be a problem. And there’s no need for unnecessary ado about nothing.
It is important for you to connect analytics through functions.php. It’s time to tell you how to do it, but first I’ll explain in which cases you really need to use this method:
You do not want to use unnecessary plugins. In vain, modularity – a convenient thing, but sometimes overloaded with unnecessary functions or do not work as expected. The reason is valid. But there is no difference whether you add custom functions in functions.php or put them in a plugin, the load will be the same.
No desire to clutter header.php or footer.php. It is quite an objective reason. It is easier to move a package of separate functions than to forge separate fragments from different files. It is better not to add anything unnecessary to templates.
There’s a child theme. This is a very common reason. Creation of a child theme is very important, it helps to keep from ruining the structure of the site during updates, loss of styles. But not always the header or footer files are transferred to the child theme.
I just want to get my head around it. That’s the most valid reason of all. I’m like that myself.
I’ve listed the main reasons, it’s time to add Metrics or Analytics via functions.php
Adding Yandex Metrics orGoogle Analytics to WordPress
In general, the ideas of such texts are born when I suddenly find out that there is some information, but the network for some reason did not tell about it. Even surprising, because to embed Metrics or Analytics through functions.php comes to mind often (but embedding in widgets is more common). Of course, an experienced WordPress user will not see any problems in this, while an inexperienced one will be sent… for a plugin.
In general, there is a simple solution – hooks. They allow you to avoid writing complex functions, not to create executable files and not to worry. It is enough to specify the necessary hook and the system will understand where the code should be embedded.
Analysts prefer to embed analytics systems in the head section. Many recommend embedding in the basement, but then the quality of information collection drops, because the “footer” is loaded later than the “head”. Therefore, we will consider the example of embedding in the head.
Embed Metrics via functions.php
First of all add the counter and get the code. Don’t forget to enable Webvisor if you need it.
Open the theme’s functions.php file and add the following lines (don’t forget to insert your counter, it starts with the line — Yandex.Metrika counter –, ends with the line — /Yandex.Metrika counter –:
add_action('wp_head', 'wp_metrikass');
function wp_metrikass() {
?>
<!-- Yandex.Metrika counter -->
<script type="text/javascript" >
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
m[i].l=1*new Date();
for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");
ym(01234567, "init", {
clickmap:true,
trackLinks:true,
accurateTrackBounce:true,
webvisor:true
});
</script>
<noscript><div><img src="https://mc.yandex.ru/watch/53708614" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
<!-- /Yandex.Metrika counter -->
<?php }
Let’s break it down in order.
The add_action function adds a specific action through the use of a hook (hook). That is, wp_head is a hook that defines where the action will be performed, in this case in the section – head – /head, I added “wp_metrikass” – a function that I will define further, its name must be unique, otherwise you should expect conflicts, so call it more sophisticated. Don’t forget to put a tag before you start the code:
?>
this will complete the php block. After inserting the Metrics script, which starts with the line – Yandex.Metrika counter – and ends with the line – /Yandex.Metrika counter – enter:
<?php
and put “}” to terminate the function. Copy your metric code. It will be output after the counter is created.
Done, Metric is added via functions.php. By the way, if you decide to insert code through the footer , use the wp_footer hook instead of wp_head. In this case, the function is activated when the basement is loaded.
Embed Google Analytics via functions.php
Are there any major differences in this case? Of course not, the principle is exactly the same. Create an action, specify the wp_head hook, create a new function. The block above will work for Analytics as well, just create a new function, otherwise conflicts are guaranteed. I’m posting the code for an example:
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-*********-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-*********-1');
</script>
<?php }
Everything is the same, the main thing is to subtly name the function, add your counter code that starts with the line — Global site tag (gtag.js) – Google Analytics — and ends with the line /script, then open a php block and bracket“}” to complete the function. It shouldn’t cause any difficulties. The principle hasn’t changed.
Additional recommendations
Create functions with a unique name only, so that the probability that they will end up in other plugins or the engine is reduced to zero. As you can see, adding counters via the functions.php file is pretty easy. Use it. This is much easier than editing the theme files. Of course, you can add code via widgets, but it’s harder to prioritize loading from them. And you can’t create a unique function either, that’s why I prefer to use this principle.