Woocommerce simple filter php

My php skills is very low. I need some help this this function.
What it should do: When a order is marked as “failed” it should redirect to the woocommerce cart with an error message.

But problem is that this code redirect ALL status to the cart with the error message (even if payment is approved).

Read More
add_action( 'woocommerce_thankyou', function(){



global $woocommerce;
$order = new WC_Order();
if ( $order->status != 'failed' ) {
wp_redirect( $woocommerce->cart->get_cart_url() );  // or whatever url you want
wc_add_notice ( __( 'Payment Failed', 'woocommerce' ), 'error');
exit;
}
});

Related posts

2 comments

  1. Currently you are cheching if status IS NOT failed and then redirect.

    Change

    if ( $order->status != 'failed' ) {
    

    to

    if ( $order->get_status() == 'failed' ) {
    

    See PHP comparison operators.

    Also, you are not getting correct order. Your function should take $order_id and load correct order.

    add_action( 'woocommerce_thankyou', function( $order_id ){
      $order = new WC_Order( $order_id );
      if ( $order->get_status() == 'failed' ) {
        wp_redirect( $woocommerce->cart->get_cart_url() );  // or whatever url you want
        wc_add_notice ( __( 'Payment Failed', 'woocommerce' ), 'error');
        exit;
      }
    }, 10, 1); 
    
  2. First of all you need to use the hook “woocommerce_order_status_failed” instead of “woocommerce_thankyou” as it will trigger only when the order status is failed.
    Secondly you need to pass the order id in the function new WC_Order() so that it will get the details of that order. and then you can use the if statement to check if the order status if failed or not. You are using wrong operator “!=” in the if statement, so it is going to cart page for All status except failed one. You should use the “==” operator so that if the order status is equal to failed only then the statement will processed. The function you are using to get url is not compatible with new version of woocommerce, However you can use get_permalink( wc_get_page_id( ‘cart’ ) ) function to get the url of cart page.

    Here is an example :

    add_action( ‘woocommerce_order_status_failed’, ‘mysite_failed’);

    function mysite_failed($order_id) {

     $url = get_permalink( wc_get_page_id( 'cart' ) );
     $order = new WC_Order( $order_id );
     if ( $order->get_status() == 'failed' ) {
     wp_redirect($url);
     wp_redirect( $woocommerce->cart->wc_get_cart_url() ); // or whatever url you want
     wc_add_notice ( __( 'Payment Failed', 'woocommerce' ), 'error');
    
    exit;
    

    }
    }

Comments are closed.