Track WPForms Submissions in Google Analytics 4
Sends a generate_lead event to Google Analytics 4 or Google Tag Manager when an AJAX WPForms form is submitted successfully.
Opens WPIDE on
Code
$wpide_wpf_event_name = 'generate_lead';
add_action( 'wp_footer', function () use ( $wpide_wpf_event_name ) {
if ( ! wp_script_is( 'wpforms', 'enqueued' ) && ! wp_script_is( 'wpforms', 'done' ) ) {
return;
}
?>
<script>
( function ( $ ) {
if ( ! $ ) { return; }
var name = <?php echo wp_json_encode( $wpide_wpf_event_name ); ?>;
$( document ).on( 'wpformsAjaxSubmitSuccess', function ( event ) {
var formId = String( $( event.target ).data( 'formid' ) || '' );
var data = { form_id: formId, form_type: 'wpforms' };
if ( typeof window.gtag === 'function' ) { window.gtag( 'event', name, data ); }
else { window.dataLayer = window.dataLayer || []; window.dataLayer.push( Object.assign( { event: name }, data ) ); }
} );
} )( window.jQuery );
</script>
<?php
}, 100 );
Notes
Turn on "Enable AJAX form submission" in each form's settings; needs gtag.js or a GTM container on the site.
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.