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 the very vanilla "Your order has been received" page. I've been trying to figure this out a bit, and I'm pretty sure I need to add an action reference to the theme functions 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
}
});
source to share
The reason this doesn't work is because this hook is at the end of execution, after the headers are sent. Therefore you cannot send a new redirect header to the client / browser.
But you are on the right track with code. This is what I would do (inspired by Howlin's answer, but much 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>";
}
});
source to share
You can copy the thank you page at: wp-content/plugins/woocommerce/templates/checkout/thankyou.php
to
wp-content/themes/themename/woocommerce/checkout/thankyou.php
and change this page. If you want to redirect to a specific page, add the following to your thankyou.php file:
<script>
window.location = 'http://example.com/some-page'
</script>
source to share