Last active
June 8, 2022 16:45
-
-
Save marklchaves/e9ee0567f7d7e1683d6ec8b27e8504c8 to your computer and use it in GitHub Desktop.
WordPress User ID tracking for GA4 using gtag.js API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php /* Leave this line out when adding the below code to child theme functions.php */ | |
/** This PHP hook supports GA4 tracking of the WordPress user ID. */ | |
add_action( 'wp_head', function () { | |
// REMEMBER TO ADD YOUR MEASUREMENT ID BELOW | |
$gtag_config = "gtag('config', 'G-ABCDEFGHIJ');"; | |
// If someone's logged in, let's track. | |
if ( is_user_logged_in() ) { | |
$gtag_config = "gtag('config', 'G-ABCDEFGHIJ', { 'user_id': '" . get_current_user_id() . "' });"; | |
// Set the user_id custom dimension to allow recording and reporting in GA4. NOT NEEDED ANYMORE | |
//$gtag_config .= "gtag('set', 'user_properties', { 'user_id': '" . get_current_user_id() . "' });"; | |
} | |
?> | |
<!-- Global site tag (gtag.js) - Google Analytics - REMEMBER TO CHANGE THE MEASUREMENT ID --> | |
<script async src="https://www.googletagmanager.com/gtag/js?id=G-ABCDEFGHIJ"></script> | |
<script> | |
window.dataLayer = window.dataLayer || []; | |
function gtag(){dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
<?php echo $gtag_config ?> | |
</script> | |
<?php | |
// Let's send an event to test the custom dimension set above. Assumes you have a "contact-us" page. | |
if( is_page( array( 'contact-us' ) ) ) { | |
// Most contact pages have a form. So, let's send a form impression event. | |
// If someone's logged in, the "user property" (custom dimension) is sent | |
// with this event. | |
echo "<script>gtag( 'event', 'FormImpression', { 'FormName': 'Contact Us' } );</script>"; | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment