Skip to content

Instantly share code, notes, and snippets.

@marklchaves
Last active October 8, 2022 07:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marklchaves/8de876377a3b6d4c29f15452822d646d to your computer and use it in GitHub Desktop.
Save marklchaves/8de876377a3b6d4c29f15452822d646d to your computer and use it in GitHub Desktop.
jQuery for sending a generate_lead event (form submission) to GA4 using WPForms and gtag.js API
/** We'll use WPForms as an example. */
jQuery(document).ready(function($){
// Trick from https://www.chrisains.com/seo/tracking-wpforms-submissions-with-google-analytics/
let $wpConfirmationDiv = $('#wpforms-confirmation-357');
if ($wpConfirmationDiv.length) {
console.log('[GA4] WPForms #357 was successfully submitted.');
gtag("event", "generate_lead", {
'form_id': 'WPForm #357', // TO DO: Try to get form ID or name here.
});
}
// Let's add another conversion to mix it up more. This just listens for the
// submit button click as a quick test. For production use, it's better to listen
// for some custom success event to avoid false positives.
$('#cme-custom-form-1-submit').click(function() {
console.log('[GA4]"Simple custom HTML form with no custom code for tracking" submit button clicked.');
gtag("event", "generate_lead", {
'form_id': 'Simple custom HTML form with no custom code for tracking', // TO DO: Try to get form ID or name here.
});
});
}); // jQuery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment