Created
September 9, 2023 12:49
-
-
Save blogjunkie/c8e0f3864a088a52c850c3740aa1e288 to your computer and use it in GitHub Desktop.
WordPress shortcode to send custom GA4 event - use it in the form confirmation message
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 // Do not copy this line | |
/** | |
* Place this shortcode in the form confirmation message. Usage: | |
* | |
* [ga4_event] will send 'form_submit' event by default | |
* [ga4_event name="submit_enquiry"] to send 'submit_enquiry' event | |
* [ga4_event name="subscribed_to_newsletter"] to send 'subscribed_to_newsletter' event | |
*/ | |
add_shortcode( 'ga4_event', 'prefix_ga4_event_shortcode' ); | |
function prefix_ga4_event_shortcode( $atts ) { | |
$atts = shortcode_atts( array( | |
'name' => 'form_submit' | |
), $atts ); | |
$gtag = "<script>jQuery( document ).ready(function($) { | |
gtag('event', '". $atts['name'] ."', { | |
'page_location': '". get_permalink() ."', | |
'page_title': '". get_the_title() ."' | |
}); | |
});</script>"; | |
return $gtag; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment