From time to time, you'll come across the need to add a tracking code in the WordPress Head section of the website. Google Analytics and some other third-party integration use this method to track visitors.
This portion of the website is often not easily accessible within the admin area of the website. It can seem like a daunting task. There are several ways of adding tracking code, and in this article, we will list a couple of options to achieve this addition successfully.
Adding Tracking Code Options
Option 1, use the plugin:
- You can use the Insert Headers and Footers plugin, and the first step is to install it on the website.
- Once you activate the plugin, go to Settings >> Insert Headers and Footers
- From there, add your code to the Scripts in the Header Box.
- If needed, you can also add code to the Footer in the box below
Option 2 – add it under header.php file.
- You can find this file under wp-content/themes/your-theme-name/header.php
- Copy the code you need and paste it just above the closing of the </head> tag.
What if you need to place a tracking code only on some specific pages?
You can add a snippet to the functions.php. This file is located under wp-content/themes/your-theme-name/functions.php
You can use the snippet below, add your tracking code under the echo, and add the ID of the page where you want the script to load.
if (is_page(add_here_page_id_of_your_page){
function custom_head_script() {
echo "Place your code here and be sure to escape any quotes with backslash";
}
add_action('wp_head', 'custom_head_script');
}
With this last option, you should be extra careful as it can easily break your site. Remember to create a backup before you start with the work, and give it a try on a staging site first.