Discover in this tutorial how to automatically assign a UTM parameter to the links of each menu of the website in WordPress, using code.
The UTM (Urchin Tracking Module) parameters are used to track visits. To know if they come from a specific campaign, a specific source…
After adding them, you can check the analytics tool you use and attribute the visits to one behavior or another.
In this case, you will learn how to add different UTM parameters depending on the location of the menu. This way, you will be able to discern how many visits to a certain page (linked in several menus) come from one menu or another.
Let’s get started:
Snippet to automatically assign a UTM parameter to the links of each menu in a WordPress theme
Add the following code at the end of functions.php or in your functionality plugin:
In this snippet you use the
nav_menu_link_attributes filter in combination with conditionals that check the location of the menu and, depending on it, add a specific UTM parameter.
This example, contemplates two menu locations, the primary and the secondary. Depending on the theme it will have different locations, in the case of Genesis Sample, the primary goes in the header and the secondary in the footer.
Therefore, you add the following parameters respectively:
This text string will be automatically added to the URL of the menu item where they click. That is to say, if the visitors click on “Contact” from the header menu, the URL https://yourwebsite.com/contact/?utm_source=header-menu will be loaded, or https://yourwebsite.com/contact/?utm_source=footer-menu if they click on it from the footer menu.
Obviously you can use the nomenclature you want. If you do, just modify accordingly in the snippet.
You can also customize it with all the UTM parameters you want:
There are quite a few tools that allow you to generate UTMs, for example this one.
The code can be applied to any WordPress theme, you just need to know its menu locations.
Now you know how to quantify how many clicks are made on an item linked from various menus and know from which location they come from.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂