77
The “woocommerce_thankyou” hook 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!
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://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' );
}
}