In my WooCommerce store I would like to redirect to a custom 'thank you page' after payment has been completed. I'm using this code:
add_action( 'template_redirect', 'myfunction' );
function myfunction( $order_id ) {
$order = wc_get_order( $order_id ); // I assume this is where I go wrong. Probably this is empty?
if ( is_checkout() && 0 == WC()->cart->get_cart_contents_count() ) {
wp_safe_redirect( home_url() ); // redirect to home if empty cart on checkout page
exit;
} else if ( is_checkout() && **somehow check if $order has been paid?** ) {
wp_safe_redirect( 'www.myurl' ); // if order has been paid for go here. this never triggers.
exit;
}
}
I assume that my problem is that the $order_id is empty, but my debugging skills suck so I don't know how to actually verify that to even get started.
I know of the $order->get_status(). I suppose this is called a method? If I try that in the place of ** ** I get a php fatal error.
Thanks for any help.
In my WooCommerce store I would like to redirect to a custom 'thank you page' after payment has been completed. I'm using this code:
add_action( 'template_redirect', 'myfunction' );
function myfunction( $order_id ) {
$order = wc_get_order( $order_id ); // I assume this is where I go wrong. Probably this is empty?
if ( is_checkout() && 0 == WC()->cart->get_cart_contents_count() ) {
wp_safe_redirect( home_url() ); // redirect to home if empty cart on checkout page
exit;
} else if ( is_checkout() && **somehow check if $order has been paid?** ) {
wp_safe_redirect( 'www.myurl' ); // if order has been paid for go here. this never triggers.
exit;
}
}
I assume that my problem is that the $order_id is empty, but my debugging skills suck so I don't know how to actually verify that to even get started.
I know of the $order->get_status(). I suppose this is called a method? If I try that in the place of ** ** I get a php fatal error.
Thanks for any help.
Share Improve this question asked Nov 11, 2019 at 11:59 JussiJussi 234 bronze badges 3 |1 Answer
Reset to default 0I figured it out. woocommerce_payment_succesful_result guided me in the right direction, although it wasn't the final answer. function is_wc_endpoint_url() is really useful here, it checks where woocommerce is about to redirect next.
// redirect empty checkouts and completed orders.
add_action( 'template_redirect', 'myfunction' );
function myfunction() {
if( is_wc_endpoint_url( 'order-received' ) && isset( $_GET['key'] ) ) {
wp_redirect('www.myurl'); // go to custom page if order has been received
exit;
}
if ( is_checkout() && 0 == WC()->cart->get_cart_contents_count() ) {
wp_safe_redirect( home_url() ); // if trying to access checkout with empty cart go back
exit;
}
}
woocommerce_payment_successful_result
to customise the redirection URL : docs.woocommerce/wc-apidocs/… – Kaperto Commented Nov 11, 2019 at 12:54