0

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.com' ); // 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.

3
  • if you want more informations about the fatal error, you can read this stackoverflow.com/questions/12769982/…
    – Kaperto
    Nov 11, 2019 at 12:45
  • in woocommerce, the cart is empty when the order is created then you cannot do that at this place. i recommend to use the filter woocommerce_payment_successful_result to customise the redirection URL : docs.woocommerce.com/wc-apidocs/…
    – Kaperto
    Nov 11, 2019 at 12:54
  • Thanks! I will take a look at this filter soon.
    – Jussi
    Nov 11, 2019 at 14:15

1 Answer 1

0

I 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.com'); // 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;
    }  
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.