As a webmaster/blogger, we always require something to track the traffic of the website. What could be the best option other than Google Analytics or Google Tag Manager.
We always face such situation as in where to add the code. So, some possibilities are header.php, footer.php of main theme or copying those file to child theme folder and adding code to header.php or footer.php in child theme.
But that’s certainly a wrong implementation. Think of a situation such as, there is a theme update of main theme, your Analytics code will be wiped off then.
So, following is the right way to add Google Analytics or Google Tag Manager Code to WordPress.
Step-1: Create a Child Theme of your main theme. Will write about it later on.
Step-2: Create functions.php inside Child Theme folder
Step-3: Add following code to your functions.php of child theme. Make sure to replace //analytics code with your Analytics or Google Tag Manager code generated from your Google Analytics or tag manager admin panel
In the above code, 15 is the “priority” for where to add the Analytics code in header. 10 being default, higher the number, lower the priority. Read more about add_filter() method from here.That means, you will the code near and before </head> of page header. To verify, if the code is actually added to your WordPress header or not.
Open Your Website, such as http://example.com in the browser, Right click and view page source and then Ctrl+F and search for “Analytics”. You will able to locate the Analytics code in WordPress Header. near to </head>
Hope this helps.
What do you think about the aforementioned method. How you used to add Google Analytics code to your WordPress blog/website before? Do you have any better method? Feel free to share in comments.
In next articles, I will be covering such small tips to enhance your WordPress installation.