Enable Google Analytics 4 Support to track WordPress AMP pages


In this article, you will learn how to set up AMP on your WordPress website and track traffic on AMP pages in Google Analytics. I am going to cover both Universal Analytics and Google Analytics 4.

What is Accelerated Mobile Pages (AMP)?

AMP is an open-source web component framework to easily create user-first and fast experiences for the web. AMP can load instantly utilising the AMP Google cache/CDN, which preloads the content before visiting the site, therefore these pages can load instantly but without the cache/CDN it still can load up to four times faster than non-AMP web pages.

How to enable AMP on WordPress?

There are multiple plugins on the WordPress Plugin Directory which can help to convert your website, but I only going to mention the official AMP plugin as this seems to be the preferred way of converting a traditional WordPress site into an AMP WordPress website.

For more videos like this, check out the ongoing AMP for WordPress video series.

Head over to the WordPress Plugin Directory and search for AMP. Download the ZIP file or install it directly from your WordPress dashboard. Once you have completed the installation you should see the below welcome page.

Source: AMP Plugin

You have 3 different options to choose from when enabling AMP on your website.

1, Standard

  • In Standard mode, your site will be completely AMP (except in cases where you opt-out of AMP for specific parts of your site), and it will use a single theme.
  • Not recommended until you can fix the detected compatibility issue(s).
  • To address plugin compatibility issue(s), you may need to use Plugin Suppression to disable incompatible plugins on AMP pages or else select an alternative AMP-compatible plugin.

2, Transitional

  • In Transitional mode, your site will have a non-AMP and an AMP version, and both will use the same theme. If the automatic mobile redirection is enabled, the AMP version of the content will be served on mobile devices. If AMP-to-AMP linking is enabled, once users are on an AMP page, they will continue navigating your AMP content.
  • Recommended since there were no theme compatibility issues detected.
  • To address plugin compatibility issue(s), you may need to use Plugin Suppression to disable incompatible plugins on AMP pages or else select an alternative AMP-compatible plugin.

3, Reader

  • In Reader mode, your site will have a non-AMP and an AMP version, and each version will use its own theme. If the automatic mobile redirection is enabled, the AMP version of the content will be served on mobile devices. If AMP-to-AMP linking is enabled, once users are on an AMP page, they will continue navigating your AMP content.
  • To address plugin compatibility issue(s), you may need to use Plugin Suppression to disable incompatible plugins on AMP pages or else select an alternative AMP-compatible plugin.

Once you have selected the preferred mode for your site which is compatible with your template. Double-check your website design and functionality to make sure it is working as expected.

As I am writing this article, there is still no official support for Google Analytics 4 and AMP. However, thanks to David Vallejo’s implementation we can now track visitors using Google Analytics 4 and AMP. After I have discovered the open-source solution, I’ve quickly put together a WordPress plugin so no manual code changes required to implement this solution.

Set up Google Analytics 4 with AMP on WordPress sites

First of all, I would like to mention the Google Site Kit plugin. This plugin can help you to set up Google’s Universal Analytics tracking on both AMP and non-AMP pages and also GA4 on non-AMP pages. (There is a probability that this plugin will add in GA4 support for AMP in the future.) Once you are done, search for the AMP Google Analytics 4 Support (Unofficial) plugin and install it on your website. If you have finished installing the plugin, head over to the settings page where you will see the below options:

Here you can simply enter your GA4 measurement id, and save your changes. You can also change the default settings and customize the analytics tag as per your own preference.

That’s it, you should see the data coming through in your Google Analytics 4 account.

Set up Google Analytics 4 with AMP on non WordPress sites

If you are not using WordPress and the official AMP plugin but still looking to use GA4 with AMP, you can use David Vallejo’s implementation;

Just add the following code to your AMP Pages:

<amp-analytics type="googleanalytics" config="/ga4.json" data-credentials="include">
<script type="application/json">
{
    "vars": {
                "GA4_MEASUREMENT_ID": "G-ROLANDF",
                "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>

View this gist on Github

Once you have inserted the above code into to your <body> of your AMP HTML, update your measurement id. Next, save the below code as ga4.json in your root folder;

{
    "cookies": {
        "_ga": {
            "value": "$IF(LINKER_PARAM(_gl, _ga),GA1.0.LINKER_PARAM(_gl, _ga),)"
        }   
    },    
    "linkers": {
        "_gl": {
            "enabled": true,
            "ids": {
                "_ga": "${clientId}"
            },
            "proxyOnly": false
        }
    },
    "triggers": {
        "page_view": {
            "enabled": "${DEFAULT_PAGEVIEW_ENABLED}",
            "on": "visible",
            "request": "ga4Pageview"
        },
        "doubleClick": {
            "enabled": "${DEFAULT_PAGEVIEW_ENABLED}",
            "on": "visible",
            "request": "ga4Dc"
        },        
        "webVitals": {
            "enabled": "${WEBVITALS_TRACKING}",
            "on": "timer",
            "timerSpec": {
                "interval": 5,
                "maxTimerLength": 4.99,
                "immediate": false
            },            
            "request": "ga4Event",
            "vars": {
              "ga4_event_name": "web_vitals"
            },
            "extraUrlParams": {
                "event__num_first_contenful_paint": "FIRST_CONTENTFUL_PAINT",
                "event__num_first_viewport_ready": "FIRST_VIEWPORT_READY",
                "event__num_make_body_visible": "MAKE_BODY_VISIBLE",
                "event__num_largest_contentful_paint": "LARGEST_CONTENTFUL_PAINT",                
                "event__num_cumulative_layout_shift": "CUMULATIVE_LAYOUT_SHIFT"                                              
            }              
        },
        "performanceTiming": {
            "enabled": "${PERFORMANCE_TIMING_TRACKING}",
            "on": "visible",
            "request": "ga4Event",
            "sampleSpec": {
              "sampleOn": "${clientId}",
              "threshold": 100
            },
            "vars": {
                "ga4_event_name": "performance_timing"
            },            
            "extraUrlParams": {                                      
                "event__num_page_load_time": "${pageLoadTime}",
                "event__num_domain_lookup_time": "${domainLookupTime}",
                "event__num_tcp_connect_time": "${tcpConnectTime}",
                "event__num_redirect_time": "${redirectTime}",
                "event__num_server_response_time": "${serverResponseTime}",
                "event__num_page_download_time": "${pageDownloadTime}",
                "event__num_content_download_time": "${contentLoadTime}",
                "event__num_dom_interactive_time": "${domInteractiveTime}"
            }  
        }                  
    },    
    "vars": {
        "documentLocation": "SOURCE_URL",
        "clientId": "CLIENT_ID(AMP_ECID_GOOGLE,,_ga,true)",
        "dataSource": "AMP"        
    },
    "extraUrlParams": {
        "sid": "$CALC(SESSION_TIMESTAMP, 1000, divide, true)",
        "sct": "SESSION_COUNT",
        "seg": "$IF($EQUALS(SESSION_ENGAGED, true),1,0)",
        "_et": "$CALC(TOTAL_ENGAGED_TIME,1000, multiply)",        
        "gcs": "$IF($EQUALS(${GOOGLE_CONSENT_ENABLED},TRUE),G10$IF($EQUALS(CONSENT_STATE,sufficient),1,0),)"                
    },    
    "extraUrlParamsReplaceMap": {
        "user__str_": "up.",
        "user__num_": "upn.",
        "event__str_": "ep.",
        "event__num_": "epn."
    },    
    "requestOrigin": "https://${GA4_ENDPOINT_HOSTNAME}",
    "requests": {
        "ga4IsFirstVisit": "$IF($EQUALS($CALC(SESSION_COUNT, $CALC($CALC(${timestamp}, 1000, divide, true),$CALC(SESSION_TIMESTAMP, 1000, divide, true), subtract), add),1), _fv, __nfv )",
        "ga4IsSessionStart": "$IF($EQUALS($CALC($CALC(${timestamp}, 1000, divide, true),$CALC(SESSION_TIMESTAMP, 1000, divide, true), subtract),0), _ss, __nss)",                
        "ga4SharedPayload": "v=2&tid=${GA4_MEASUREMENT_ID}&ds=${dataSource}&_p=${pageViewId}&cid=${clientId}&ul=${browserLanguage}&sr=${screenWidth}x${screenHeight}&_s=${requestCount}&dl=${documentLocation}&dr=${externalReferrer}&dt=${title}&${ga4IsFirstVisit}=1&${ga4IsSessionStart}=1",
        "ga4Pageview": {
            "baseUrl": "/g/collect?${ga4SharedPayload}&en=page_view"
        },        
        "ga4Event": {
            "baseUrl": "/g/collect?${ga4SharedPayload}&en=${ga4_event_name}"
        },
        "ga4Dc": {
            "origin": "https://stats.g.doubleclick.net",
            "baseUrl": "/g/collect?v=2&tid=${GA4_MEASUREMENT_ID}&cid=${clientId}&aip=1"
        }
    }
}

View this gist on Github

That’s it, you should see tracking data in your Google Analytics 4 account.

If you notice any bugs or just need help with this implementation comment below and I’ll try to help 🙂

Did you like this article? Make sure to check out my digital tool collection. I also write about web development, design and digital marketing, so if you would like to read more, head over to my blog.

Sources: AMP Plugin, AMP Google Analytics 4 Support, David Vallejo