Add Google Conversion OnClick Function To Gravity Forms Submit Button
Add Google Conversion OnClick Function To Gravity Forms Submit Button
Today we have another quick code snippet that you can copy/paste and quickly implement into your WordPress website that features Gravity Forms.
Everybody wants to know conversion data, it’s how marketing decisions are made. Fortunately, it’s pretty easy to do. Here’s a quick example on how you could add an onclick event to a Gravity Form submit button. Before adding the onclick event, Google will provide you with additional site-specific tracking code that needs to be placed within your header file of the active theme. Take care of those instructions first. Once it comes time to add the onclick event, open up the functions.php file from your active theme and add the following:
add_filter( 'gform_submit_button_1', 'add_ga_onclick', 10, 2 ); function add_ga_onclick( $button, $form ) { $dom = new DOMDocument(); $dom->loadHTML( $button ); $input = $dom->getElementsByTagName( 'input' )->item(0); $onclick = $input->getAttribute( 'onclick' ); $permalink = get_permalink(); $onclick .= " return gtag_report_conversion(" . $permalink . ");"; $input->setAttribute( 'onclick', $onclick ); return $dom->saveHtml( $input ); }
The only modification you will want to make to the above code is on the first line, ‘gform_submit_button_1’. You will want to change the ‘_1’ with the number ID of your Gravity Form.
Other than that, implement and enjoy conversion data!
Many thanks for sharing, very useful and implemented here now.
Brilliant, thanks for this.
I am assuming that if I wanted to add the tracking to multiple buttons it would be as simple as adding multiple filters?
e.g.
add_filter( ‘gform_submit_button_1’, ‘add_ga_onclick’, 10, 2 );
add_filter( ‘gform_submit_button_2’, ‘add_ga_onclick’, 10, 2 );
add_filter( ‘gform_submit_button_3’, ‘add_ga_onclick’, 10, 2 );
function add_ga_onclick( $button, $form ) {
$dom = new DOMDocument();
$dom->loadHTML( $button );
$input = $dom->getElementsByTagName( ‘input’ )->item(0);
$onclick = $input->getAttribute( ‘onclick’ );
$permalink = get_permalink();
$onclick .= ” return gtag_report_conversion(” . $permalink . “);”;
$input->setAttribute( ‘onclick’, $onclick );
return $dom->saveHtml( $input );
}