Add Google Conversion OnClick Function To Gravity Forms Submit Button


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







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!


Share Your Thoughts

Leave a Reply

Your email address will not be published. Required fields are marked *


Related Stuff You Might Like







20% Off WP Engine

WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!