Skip to content
Home » Google Analytics 4 Support for AMP pages

Google Analytics 4 Support for AMP pages

After going through a lot of blog posts and discussions on the internet. I found a working solution with a magic code snippet.

As you know the new Google Analytics 4 (GA4) will be the only analytics processing the data and working from July 1, 2023. Read more here.

The universal analytics is shutting down processing of the data. Also we can not migrate the data from Universal Analytics (GA3) to GA4, that’s sad. Whilst we have these problems, many sites which are using AMP and put a lot of efforts and time on building AMP pages, did not have direct solutions to get GA4 working on AMP pages. No solution on topics here also.

AMP Google Analytics 4 Support – WordPress plugin | WordPress.org

Google Analytics 4 + Google AMP


There are two ways to implement it.

  1. Custom Code for AMP with <amp-analytics>
  2. A WordPress plugin (no code required)

So lets dive in..

1. Custom Code for AMP with <amp-analytics>

After reading the article of David, here’s the magic code snippet to use on AMP pages, that just works!

<amp-analytics type="googleanalytics" config="https://amp.analytics-debugger.com/ga4.json" data-credentials="include">
<script type="application/json">
{
    "vars": {
                "GA4_MEASUREMENT_ID": "G-XXXXXXXXXX",
                "GA4_ENDPOINT_HOSTNAME": "www.google-analytics.com",
                "DEFAULT_PAGEVIEW_ENABLED": true,    
                "GOOGLE_CONSENT_ENABLED": false,
                "WEBVITALS_TRACKING": false,
                "PERFORMANCE_TIMING_TRACKING": false
    }
}
</script>
</amp-analytics>

Note: Please replace “G-XXXXXXXXXX” with your GA4 measurement ID in the above snippet and place that code in footer of your AMP pages.

Also you can self host this ga4 json in your project or site and then use self-hosted ga4.json path in “config” attribute of `<amp-analytics>` to make it more reliable. https://amp.analytics-debugger.com/ga4.json

Please go through this article for advanced configuration and tracking data with GA4 on AMP pages – https://www.thyngster.com/how-to-track-amp-pages-with-google-analytics-4

2. A WordPress plugin (no code required)

For WordPress CMS, you can use this plugin to make it work on AMP – https://wordpress.org/plugins/amp-google-analytics-4-support/

You can see the backend options after activating this plugin.

backend settings of WordPress plugin

This ultimately outputs this which is required for AMP GA 4 tracking.

front-end source code

Credits

Roland Farkas – https://github.com/rolandfarkasCOM
David Vallejo – https://github.com/thyngster – https://github.com/analytics-debugger/google-analytics-4-for-amp/blob/main/ga4.json

2 thoughts on “Google Analytics 4 Support for AMP pages”

Leave a Reply

Your email address will not be published.