I have an old website that's using the old Google Analytics code from last decade, and I need help using the new GA4.
Old Code (2016)
To send custom events and pageviews to Google, I would use the global ga()
function from their <script>
snippet:
// Event
ga('send', 'event', {
eventAction: 'click',
eventCategory: 'social',
eventLabel: 'twitter'
});
// Pageview
ga('send', {
hitType: 'pageview',
page: 'Video page',
title: 'Intro video'
});
New Code (2022)
Google Analytics says that all old properties will stop working on July 1, 2023, so we need to switch to the new Google Analytics 4 property, the <script>
snippet in the header has changed a bit, now it creates gtag()
:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=X-XXX123456"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'X-XXX123456');
</script>
But upon trying to use gtag("send")
like I used to, it looks like nothing gets transmitted to Google anymore. I've tried looking it up, but all tutorials/articles still demonstrate the old approach. How can I send custom events using the new GA4?