Posted on

Setting a page as a blog post or regular page

I have been asked a few times to count blog traffic differently from traffic to other parts of the site. Presumably, this is to see if the blog actually does anything in the conversion funnel.

For most WordPress sites, the blog is in its own directory, so its easy. You can just set up a trigger on page view with the condition, page path contains ‘blog’.

However, there are some permalink structures that put everything in the root, so its not easy to identify which pages are pages and which ones are posts. For example, this site has no /blog/ structure.

My first thought was to view the source and see if there is anything in the code that differentiates a blog and a page. I found

@type”:”BlogPosting”
@type”:”Article”

in some schema that RankMath SEO was producing. If only I could parse this or test if it contained ‘BlogPosting’

So I found the solution here on stack overflow. Well a similar one with Yoast SEO. Basically, the problem is how to parse JSON with Javascript.

function() {
  var publishedDate = "";
  var yoastInfo = JSON.parse(document.head.querySelector('.yoast-schema-graph.yoast-schema-graph--main').innerHTML); 
  vars = yoastInfo["@graph"];
  for(var i in vars) {
    if(vars[i]['@type'] === 'WebPage') {
      publishedDate=(vars[i]['datePublished']); 
    }
  }



  return publishedDate;
}

I managed to modify that function to work with Rank Math and check if any of the @types are BlogPostings.

function() {
  var blog = false;
  var Info = JSON.parse(document.head.querySelector('.rank-math-schema').innerHTML); 
  vars = Info["@graph"];
  for(var i in vars) {
    if(vars[i]['@type'] === 'BlogPosting') {
      blog = true; 
    }
  }



  return blog;
}

So that returns true for any page that is a blog post.

The Plugin Way

There is a plugin called Google Tag Manager for WordPress. It populates the data layer with the post type and you can grab that in tag manager.

You can create an event called viewed_blog when the post type is blog. Its all straightforward to do. If you view the source to this page and look for datalayer,

var dataLayer_content={“pagePostType”:”post”,”pagePostType2″:”single-post”,”pageCategory”:[“tips”],”pagePostAuthor”:”Ben”}

you’ll get something like that. Just create a custom variable that takes the value of the “pagePostType”.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *