How do I access a custom taxonomy created in Wordpress in Google Tag Manager?

154 Views Asked by At

I created a custom taxonomy in WordPress for article lengths. It's called 'Length' and these are the items within it: image

I also created a custom dimension in Google Analytics (it's index 5), and created a custom Data Layer variable in Google Tag Manager for it. But I think I am referencing the Data Layer Variable Name incorrectly and it is 'undefined' when I preview it in gtm.

I can see the taxonomy 'length' and it's classification 'standard' at the end of the class when I inspect the page, but I can't figure out what the Data Layer Variable Name is (I know I need to use dot notation).

Here's the code that shows when I inspect.

<article id="post-2784" class="post post-2784 type-post status-publish format-standard has-post-thumbnail hentry category-deforestacion category-gran-chaco length-standard">
...
</article>

How do I access the taxonomy correctly for gtm? I'm pretty sure it's just this that is incorrect and spent hours debugging and researching but can't figure it out.

2

There are 2 best solutions below

0
Ld91049 On BEST ANSWER

I didn't try exactly what was suggested but for those wondering this is what worked for me:

function(){
  
  var length = document.querySelector(".status-publish.post").className.split('length-')[1].split(' ')[0];
 return length; 

}

I had an issue where it would track the dimensions on the homepage too (due to the wordpress theme), so I wrapped it in an if:

    function(){
  var pagePath1 = document.location.pathname.split('?')[0];
  
  if (pagePath1 == '/' ){
} else {
  
  var length = document.querySelector(".status-publish.post").className.split('length-')[1].split(' ')[0];
 return length; 
}
}

It works perfectly with my custom dimensions in Google Analytics and my custom taxonomies in Wordpress!

4
BNazaruk On

dataLayer is a global variable on your pages. Try opening dev console on the article page and type dataLayer in it. I heavily doubt it's populated though unless your the taxonomy extension is better than 90% of extensions out there.

You don't need a DL though. If you want to populate your custom dimension on the page view, just have a custom JS code variable that would look something like this:

function(){
   return document.querySelector(".status-publish.post").className.split(' ').find(function(x) {x.startsWith('length-')});
}

And then just use it instead of the DL variable. It takes whatever first has .status-publish.post on the page and returns the first class that has length- in it. The logic assumes certain things. You should try and adjust it to your page design, especially if there are multiple .status-publish.post items on the pages.