Woocommerce action hook to redirect to custom thank you page

23,576

Solution 1

JavaScript redirect? Seriously?

You can use template_redirect with no problems.

Example:

add_action( 'template_redirect', 'correct_redirect' );

function correct_redirect(){

    /* we need only thank you page */
    if( is_wc_endpoint_url( 'order-received' ) && isset( $_GET['key'] ) ) {
        wp_redirect('any url');
        exit;
    }
}

You can find more examples with redirects here https://rudrastyh.com/woocommerce/thank-you-page.html#redirects

Solution 2

The reason why that doesn't work is because that hook is to late in the execution, after the headers have been sent. Therefor you can not send a new redirect header to the client/browser.

But you are on the right way with your code. This is what I would do(inspired by Howlin's response, but a lot cleaner):

add_action( 'woocommerce_thankyou', function( $order_id ){
    $order = new WC_Order( $order_id );

    $url = 'http://redirect-here.com';

    if ( $order->status != 'failed' ) { 
        echo "<script type=\"text/javascript\">window.location = '".$url."'</script>";
    }
});
Share:
23,576
Admin
Author by

Admin

Updated on July 03, 2020

Comments

  • Admin
    Admin almost 4 years

    I want to redirect to a custom page after my customers make a payment. Now it goes to a very vanilla, "Your order has been received" page. I have been trying to figure this out for a bit and I'm pretty sure I have to add an action hook to my themes function file. And I found some code that I thought would work but it doesn't.

    add_action( 'woocommerce_thankyou', function(){
    
    
    
    global $woocommerce;
    $order = new WC_Order();
    if ( $order->status != 'failed' ) {
    wp_redirect( home_url() ); exit; // or whatever url you want
    }
    });