• As I’m imagining this plugin is really only used by other developers, here’s some sample code I’m using that is hooking into Google Analytics, and outputting the category or “primary category” as an additional parameter to be viewed under the page_view event.

    the part you might find helpful is

    // get the term object for the primary category and assign it to our variable

    $primary_category_id = get_post_meta( $post_id, 'epc_primary_category', true );

    $postCategory = get_term( $primary_category_id )->name;



    This is what I place in our single.php template for blog posts.

    
    
    <?php
      $categories = get_the_category();
      $category_names = array();
      foreach ($categories as $category) {
        $category_names[] = $category->name;
      }
      $postCategory = implode(', ', $category_names);
    
      // run only if the post has a designated primary category, which is done through the Easy Primary Category plugin
      if ( get_post_meta( $post_id, 'epc_primary_category', true ) ) {
        // get the term object for the primary category and assign it to our variable
        $primary_category_id = get_post_meta( $post_id, 'epc_primary_category', true );
        $postCategory = get_term( $primary_category_id )->name;
      }
    ?>
    
    
    <script>
      const postCategory = '<?php echo $categories_string; ?>';
    // if the current page starts with /blog/ but isn't the blog index page, then look for the javascript variable postCategory and send that to GA4
    if(currentPath.startsWith('/blog/') && currentPath !== '/blog/'){
    	if(typeof postCategories !== 'undefined'){
    		// send event to GA4
    		gtag('event', 'page_view', {
    			'blog_category': postCategories
    		});
    	}
    }
    </script>
  • The topic ‘An example about how to use this in your theme’ is closed to new replies.