Track Gravity Forms Submissions in Google Analytics 4
Sends a generate_lead event to Google Analytics 4 or Google Tag Manager when a Gravity Forms form shows its confirmation, including AJAX forms.
Opens WPIDE on
Code
$wpide_gf_event_name = 'generate_lead';
add_action( 'wp_footer', function () use ( $wpide_gf_event_name ) {
if ( ! wp_script_is( 'gform_gravityforms', 'enqueued' ) && ! wp_script_is( 'gform_gravityforms', 'done' ) ) {
return;
}
?>
<script>
( function () {
var name = <?php echo wp_json_encode( $wpide_gf_event_name ); ?>;
function send( formId ) {
var data = { form_id: String( formId ), form_type: 'gravity-forms' };
if ( typeof window.gtag === 'function' ) { window.gtag( 'event', name, data ); }
else { window.dataLayer = window.dataLayer || []; window.dataLayer.push( Object.assign( { event: name }, data ) ); }
}
if ( window.jQuery ) {
window.jQuery( document ).on( 'gform_confirmation_loaded', function ( event, formId ) { send( formId ); } );
}
document.querySelectorAll( '.gform_confirmation_wrapper' ).forEach( function ( el ) {
var match = el.id.match( /gform_confirmation_wrapper_(\d+)/ );
if ( match ) { send( match[1] ); }
} );
} )();
</script>
<?php
}, 100 );
Notes
Needs gtag.js or a GTM container already on the site; non-AJAX forms are tracked when the confirmation page loads.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.