Home » WooCommerce: Disable Tracking if Order Failed @ Thank You Page

WooCommerce: Disable Tracking if Order Failed @ Thank You Page

by Tutor Aspire

The “woocommerce_thankyouhook fires on the Thank You page once an order is placed. Most tracking functions like Google Analytics, affiliate commission plugins and other WooCommerce extensions rely on “woocommerce_thankyou” to run their code.

Problem is – “woocommerce_thankyou” is ALSO called if an order fails (i.e. payment did not go through). Now, unless the plugin is smart enough in its own functions to exclude failed orders, which doesn’t happen often I’m afraid, we need to find a way NOT to run “woocommerce_thankyou” if an order fails. Case study: a client uses a third party affiliate plugin, this plugin hooks into “woocommerce_thankyou“, but they don’t want to calculate conversions when an order fails.

So here you go!

The default Thank You page in WooCommerce

PHP Snippet: Disable “woocommerce_thankyou” Action if WooCommerce Order = Failed

/**
 * @snippet       Remove "woocommerce_thankyou" Action if Order Fails - WooCommerce
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 3.9
 * @donate $9     https://www.tutoraspire.com
 */
 
add_action( 'wp_head', 'tutoraspire_tracking_exclude_failed_orders' );
 
function tutoraspire_tracking_exclude_failed_orders() {
   global $wp;
   // ONLY RUN ON THANK YOU PAGE
   if ( ! is_wc_endpoint_url( 'order-received' ) ) return; 
   // GET ORDER ID FROM URL
   $order_id = absint( $wp->query_vars['order-received'] );
   $order = wc_get_order( $order_id );
   if ( $order->has_status( 'failed' ) ) {
      // DISABLE ANY FUNCTION HOOKED TO "woocommerce_thankyou"
      remove_all_actions( 'woocommerce_thankyou' );
   }
}

You may also like