user3905752
user3905752

Reputation: 61

Woocommerce action hook to redirect to custom thank you page

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
}
});

Upvotes: 6

Views: 28806

Answers (3)

Misha Rudrastyh
Misha Rudrastyh

Reputation: 873

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

Upvotes: 10

Pelmered
Pelmered

Reputation: 2882

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>";
    }
});

Upvotes: 5

Howli
Howli

Reputation: 12469

You could copy the thank you page at: wp-content/plugins/woocommerce/templates/checkout/thankyou.php to

wp-content/themes/themename/woocommerce/checkout/thankyou.php and modify that that page. If you want to redirect to a specific page add the following to the thankyou.php file:

<script>
    window.location = 'http://example.com/some-page'
</script>

Upvotes: 0

Related Questions