Skip to content

Instantly share code, notes, and snippets.

@michaeldozark
Last active August 29, 2015 14:01
Show Gist options
  • Save michaeldozark/33ecc4b25266bd56a356 to your computer and use it in GitHub Desktop.
Save michaeldozark/33ecc4b25266bd56a356 to your computer and use it in GitHub Desktop.
Adds Google Analytics Tracking for Gravity Forms.
<?php
add_filter( "gform_submit_button", "slimline_gform_google_analytics", 10, 2 ); // add Google Analytics tracking to form submits
/**
* slimline_gform_google_analytics function
*
* Adds Google Analytics Tracking for Gravity Forms.
*
* @global object $wp The WordPress global object. Used for capturing the current request URI {@see http://kovshenin.com/2012/current-url-in-wordpress/}
* @param string $button_input Submit button HTML
* @param object $form The current form
* @return string Submit button HTML with Google Analytics event tracking added
* @see http://www.danielauener.com/setting-up-gravity-forms-analytics-goals/
* @since 0.6.0
*/
function slimline_gform_google_analytics( $button_input, $form ) {
global $wp;
$dom = new DOMDocument();
$dom->loadHTML( $button_input );
$input = $dom->getElementsByTagName( 'input' )->item(0);
$action = sanitize_title( $form[ 'title' ] );
parse_str( $_SERVER[ 'QUERY_STRING' ], $query_args );
$url = home_url( add_query_arg( $query_args, $wp->request ) );
if ( $input->hasAttribute( 'onclick' ) ) {
$input->setAttribute( "onclick", "_gaq.push(['_trackEvent', 'web-form', '{$action}', '{$url}',, false]); {$input->getAttribute( 'onclick' )}" );
} else {
$input->setAttribute( "onclick", "_gaq.push(['_trackEvent', 'web-form', '{$action}', '{$url}',, false]);" );
}
return $dom->saveHtml( $input );
}
@jg314
Copy link

jg314 commented Mar 20, 2015

Does this account for when people try to submit a form that has errors in it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment