By now you’ve had some type of exposure to Google’s new Tag Manager. If you haven’t read my last post on how to use Google Tag Manager.
This post is going to be a bit more technical, but hopefully you’ll find it useful.
Recently, I wanted to run a test to see if I could compare how various categories on my wordpress site perform against each other. Using GTM, I was able to set up a quick hack to make this happen.
First, you’ll want to make sure that you have an empty data layer in your header file. This needs to go above your Google Tag Manager code so that it can be executed properly.
It will look like this:
Simple right? Next you’ll want to add this bit of code to your single.php file:
Be sure to publish your pages and empty your cache once these changes have been made.
This fantastic piece of code is courtesy of Julien Coquet and contains a few changes to his original code. I put mine right after the end loop code in WordPress on the single.php page.
As you can see above, the code is calling a few items. Those are:
- The post author’s name
- The post type
- The number of comments
- The category
- The tags
- The publish date
Next, you’ll want to log into your Google Tag Manager and go to your container and add these as macros.
You can call your macro whatever you want and you’ll choose ‘Data Layer Variable’ for your macro type.
If you’re creating one for the Author you could call it WP Author. In the data layer variable name, you’ll call it GTM_WP_authorname.
Once you’ve added all of your data layer variables, you’ll go to your Google Analytics tag and go to more settings. Under more settings you’ll choose Custom Variables and select new. Choose your first slot and Name it Author name (This is what will appear as the variable in Google Analytics.) For the value, choose your macro WP Author and choose Page Level for scope. Repeat this process for up to five variables.
This is where it gets interesting. After trial and error, I discovered that if you don’t tell it to stop, the GTM code will fire before the page renders and it won’t record the custom variables on the page. One way around this is to create a custom rule for your blog pages.
In my case, I created a new rule that equals the event gtm.dom and url contains /blog/. This simple script will only fire on blog pages once the entire page has loaded. In this case, I also created another rule that will fire on all pages not containing /blog/ as soon as the page loads.
If you want to check your work, I suggest using this plugin called WASP. The Web Analytics Solution Profiler has been really helpful to help debug what’s going on with my pages.