Search code examples
phpwordpresswoocommerceendpointpayment-method

redirect to different url after order received or/ Redirect to custom Thankyou page after WooCommerce orders paid


After successful payment through Razorpay payment gateway, I need to redirect to my custom created Thankyou page, instead of Razorpay payment gateway plugin default redirect URL.

My problem illustrated: screen recorded video

Here is what I tried in functions.php file:

/* Redirect WooCommerce to a custom page after checkout */
add_action( 'woocommerce_thankyou', 're_redirect_woo_checkout');
function re_redirect_woo_checkout( $order_id ){
    $order = wc_get_order( $order_id );
    $url = 'custom thankyou page url here';
    if ( ! $order->has_status( 'failed' ) ) {
        wp_safe_redirect( $url );
        exit;
    }
}

It work which have zero payment product that doesn't need razorpay gateway to popup to pay, it auto redirect instant when clicking proceed to checkout. But when clicking proceed to checkout for payment above zero cost then razorpay gateway popup required to pay through different paying facility, after successfull payment through razorpay payment gateway it's not redirecting to my specific choice of page (custom thank you page).


Solution

  • finally i came up with this code and its worked

    add_action( 'template_redirect', 'wc_thank_you_redirect' );
    function wc_thank_you_redirect(){ 
      if( isset( $_GET['key'] ) && is_wc_endpoint_url( 'order-received' ) ) { //change order-received to your endpoint if you will change it in the future 
        $order_id = wc_get_order_id_by_order_key( $_GET['key'] );
        if ( ! empty( $order_id ) ) {
          $order = wc_get_order( $order_id );
          $order_status = $order->get_status();
            
            if ('failed' == $order_status ) {  //failed order status
              wp_redirect( 'your custom failed page url here' ); //change url here
              exit;
            } else {
              wp_redirect( 'your custom thank you page url here' ); //change url here for other statuses redirect
              exit;
            }
          }
        }
      }
    //code end for redirect after order received