How to track WordPress Author and Categories in Google Analytics in one piece of code?

Our NPO needs to be able to track author and category information from our WordPress website in Google Analytics. I’ve set up a Content Grouping for Author and set it to Slot 1 and one for Category and set it to Slot 2.

In WordPress I have Google Analytics for Yoast and in Advanced > Custom Code I put code I found StackOverflow:

Read More
    <?php 
   if (is_single()){
      echo "ga('set', contentGroup1, '".get_the_author()."');n";
      $category = get_the_category();
      if ($category && !empty($category[0]->cat_name)){
         echo "ga('set', contentGroup2, '".$category[0]->cat_name."');n”;
      }
   }
?>

However this had the very undesired effect of reducing our tracked traffic to zero in Google Analytics. Going into Behaviour > All Pages > Sort Type: Author or Category all the traffic stats for the whole site were now shown only in there, and set as ‘Undefined’. Everything only went back to normal when the code in Yoast was deleted.

Does anybody have a piece of code that will track wordpress authors and categories successfully?

Thanks!

Related posts