Push custom events to Google Tag Manager and Analytics

Continuing the discussion from Integrating Google Tag Manager with Google Analytics:

Pushing custom events to Google Tag Manager and Analytics

:bookmark: This guide explains how to configure your Discourse site to send custom events to Google Tag Manager (GTM) and Google Analytics, allowing you to track specific user interactions.

:person_raising_hand: Required user level: Administrator

Prerequisites

Before implementing custom events, ensure you have:

  1. Configured Google Tag Manager on your Discourse site by following the Setup Google Tag Manager for Analytics guide
  2. Added your GTM container ID to your site’s gtm container id setting
  3. Updated your site’s content security policy script src setting to allow Google scripts

Adding custom events

Create a theme component

  1. Navigate to Admin > Customize > Themes
  2. Click “New” and select “Create new component”
  3. Give your component a name
  4. Add code to the component’s /head section. For example, the code below takes appEvent triggers and pushes the following events to the dataLayer:
  • post:liked
  • post:created
  • topic:created
<script type="text/discourse-plugin" version="0.11.0">
window.dataLayer = window.dataLayer || [];

// Track post likes
api.onAppEvent("page:like-toggled", (post, likeAction) => {
  let topic = post.topic;
  if (post && topic && likeAction && likeAction.acted) {
    window.dataLayer.push({
      'event': 'postLiked',
      'postId': post.id
    });
  }
});

// Track new posts
api.onAppEvent("post:created", post => {
  if (post) {
    window.dataLayer.push({
      'event': 'postCreated',
      'postId': post.id
    });
  }
});

// Track new topics
api.onAppEvent("topic:created", (post, composerModel) => {
  if (post) {
    window.dataLayer.push({
      'event': 'topicCreated',
      'topicCategory': composerModel.get("category.name"),
      'topicId': post.topic_id
    });
  }
});

</script>
  1. Save the component
  2. Add the component to all active themes on your site

Available events

All available trigger events are listed here: AppEvents triggers reference

Configuring GTM

Create a trigger

  1. Go to https://tagmanager.google.com/
  2. Select “Triggers” from the side menu
  3. Click “New”
  4. Name your trigger
  5. Select “Custom Event” as the Trigger type
  6. Enter the event name (e.g., postCreated)
  7. Set the trigger to fire on “All Custom Events”

Create a Data Layer variable

  1. Select “Variables” from the GTM side menu
  2. Click “New” in the User-Defined Variables section
  3. Name your variable
  4. Select “Data Layer Variable” as the Variable Type
  5. Enter the data layer variable name (e.g., postCreated)
  6. Set Data Layer Version to “Version 2”

Create a Google Tag for Event Tracking

:information_source: As of 2024, the recommended approach is to use the new “Google Tag” template instead of the older “Google Analytics: GA4 Event” tag type. The Google Tag provides better integration with GA4 and includes built-in support for Consent Mode v2.

  1. Select “Tags” from the GTM side menu
  2. Click “New”
  3. Name your tag (e.g., “GT - Post Created”)
  4. Under Tag Configuration:
    • Select “Google Tag”
    • Select your GA4 Configuration (or create a new one if this is your first tag)
    • For “Event Name”, enter a descriptive name following GA4 naming conventions (e.g., post_created)
    • Under “Configuration settings”, click “Add Row” to include your data layer variables:
      • Configuration Parameter: (e.g., postId)
      • Value: Your data layer variable (e.g., {{postCreated}})
  5. Under “Triggering”:
    • Select your previously created custom event trigger

:warning: If you’re currently using “Google Analytics: GA4 Event” tags, they will continue to work, but new implementations should use the “Google Tag” template for better future compatibility and features.

Event Naming Requirements

GA has specific requirements for event names:

  • Use snake_case (lowercase letters with underscores)
  • Maximum length of 40 characters
  • Can only contain alphanumeric characters and underscores

Testing your Google Tag

  1. Click the “Preview” button in GTM
  2. Navigate to your Discourse site
  3. Perform the action you want to track (e.g., create a post)
  4. In the GTM Preview mode:
    • Verify that your custom event appears in the left panel
    • Check that your Google Tag fired correctly
    • Confirm that all parameters are being passed as expected
  5. In Google Analytics:
    • Navigate to Configure > Events
    • Your custom event should appear in the list after it has been triggered
    • Note: it may take up to 24 hours for new events to appear in GA4 reports

:information_source: You can use the GA4 DebugView to see real-time event data during testing.

Troubleshooting

If you’re not seeing events in GTM:

  1. Check that your GTM container ID is correctly set in Discourse
  2. Ensure your theme component is added to all active themes
  3. Add console.log statements to verify the events are firing:
api.onAppEvent("post:created", post => {
  console.log("post:created event triggered");
  if (post) {
    window.dataLayer.push({
      'event': 'postCreated',
      'postId': post.id
    });
  }
});
  1. Use the Simple Data Layer Viewer Chrome extension to monitor the data layer
  2. If you see Content Security Policy (CSP) errors, please refer to the prerequisites referenced above, and review Mitigate XSS Attacks with Content Security Policy for further steps.

:warning: If you have the ga universal tracking code site setting configured, empty it as GTM will handle the tracking script.

Last edited by @MarkDoerr 2024-12-10T01:05:06Z

Check documentPerform check on document:
11 Likes

We’ve updated this topic to reflect the changes that GTM and GA have undergone since it was originally published. We’ve also cleaned out the comments as many of them referenced that outdated information.

2 Likes