WordPress Gravity Form | Add google conversion onclick function to forms submit button

This time, our adv manager, ask me to know conversion data of a landing page.
So, i adds a “onClick” event to a gravity form submit button.
Before we can add the event, we need to place, site specific tracking code, in the header file of the active theme.
Here an example of code to put in header ( before the closing tag ) :

 function gtag_report_conversion(url) {
  var callback = function () {
  if (typeof(url) != 'undefined') {
   window.location = url;
  }
  };
  gtag('event', 'conversion', {
     'send_to': 'AW-700953485/fdszCP6s9LIBEI6nns4C',
     'event_callback': callback
  });
  return false;
   }

Next, we need to add the onClick event, let’s open the function.php of your theme and add the following snippet :

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 things you need to change is ‘gform_submit_button_1’ with the id of your button.
The ID of the button can be simply find by clicking right mouse button on the form button and select “inspect”.

You can test you conversion with “Google Tag Assistant ” extension.

That’s all !