How to Set Up Content Grouping in Google Analytics 4 for WordPress via Google Tag Manager

Content Groups is a powerful feature in Google Analytics 4 (GA4) that allows you to categorize your content or e-commerce traffic into logical groups, such as blog categories, page sections, products, or article types, for better performance analysis across different content themes.
When using WordPress as your CMS, leveraging built-in categories is a logical way to group content. This guide walks you through implementing content grouping using WordPress categories, Google Tag Manager (GTM), and Google Analytics 4 (GA4).
Table of ContentsStep 1: Understand How Content Groups Work in GA4Step 2: Expose WordPress Categories to the Front EndStep 3: Create a GTM Variable to Capture the CategoriesStep 4: Modify your GA4 pageview tag to include the content groupStep 6: Register a Custom Definition in GA4Step 7: Build Reports Using the Content Group DimensionFurther Customization
Step 1: Understand How Content Groups Work in GA4
In GA4, content grouping is achieved by creating a custom dimension that can be used in reports to view metrics grouped by your defined logic. Unlike UA, GA4 does not offer a native content grouping setting in the user interface. Instead, you must send a parameter such as content_group with each event, typically the pageview event.
Step 2: Expose WordPress Categories to the Front End
Google Tag Manager can only access data rendered in the page or exposed via JavaScript. Therefore, you must ensure your WordPress theme outputs the current post’s categories in a format that GTM can access.
Use a Data Layer Push in Your Child Theme
Insert the following snippet into your theme’s functions.php file to push category data to the GTM data layer:
add_action(‘wp_head’, ‘inject_primary_category_data_layer’);
function inject_primary_category_data_layer() {
if (is_single()) {
global $post;
$category_name = ‘Uncategorized’;

// For standard posts, use category logic
elseif ($post_type === ‘post’) {

// Rank Math’s primary category
if ($category_name === ‘Uncategorized’) {
$rank_math_primary_id = get_post_meta($post->ID, ‘rank_math_primary_category’, true);
if ($rank_math_primary_id) {
$term = get_term($rank_math_primary_id);
if (!is_wp_error($term) && isset($term->name)) {
$category_name = $term->name;
}
}
}

// Fallback to first assigned category
if ($category_name === ‘Uncategorized’) {
$categories = get_the_category($post->ID);
if (!empty($categories) && !is_wp_error($categories)) {
$category_name = $categories[0]->name;
}
}
}

// Output the result to the dataLayer
echo “

Scroll to Top