Woocommerce redirect thankyou page based on product ID doesn’t empty Cart

Your actual code is a bit outdated and not so secure… Since WooCommerce 3 Order items are now Objects and $item['product_id'] is replaced by $item->get_product_id().

You should try first to use woocommerce_get_return_url like:

add_action( 'woocommerce_get_return_url', 'custom_order_received_return_url', 10, 2 );
function custom_order_received_redirect( $return_url, $order ){
    // HERE define your products IDs in the array
    $product_ids = array(741);

    // HERE define your redirection URL (with the order ID as argument if needed)
    $redirection_url = home_url('/ar1m/');

    if ( is_ssl() || get_option( 'woocommerce_force_ssl_checkout' ) == 'yes' ) {
        $redirection_url = str_replace( 'http:', 'https:', $redirection_url );
    }

    // Loop through order items
    foreach( $order->get_items() as $item ) {
        if( in_array( $item->get_product_id(), $product_ids ) ) {
            return $redirection_url;
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). It should works.


If not, the following code will make a custom redirection on “Order received” page for defined product ID(s), emptying cart (if needed) and checking that the order is valid:

add_action( 'template_redirect', 'custom_order_received_redirect' );
function custom_order_received_redirect(){
    // Only on order received (thankyou) page for a valid Order ID
    if( is_wc_endpoint_url('order-received')
        && ( $order_id = absint( get_query_var('order-received') ) )
        && get_post_type($order_id) === 'shop_order'
        && isset( $_GET['key'] ) ) {

        // Empty cart
        if ( ! WC()->cart->is_empty() ) {
            WC()->cart->empty_cart();
        }

        // Get an instance of the WC_Order Object
        $order = wc_get_order( $order_id );

        // Check that the order key is valid
        if( is_a($order, 'WC_Order') && $order->get_order_key() === esc_attr($_GET['key']) ) {

            // HERE define your products IDs in the array
            $product_ids = array(2781);

            // HERE define your redirection URL (with the order ID as argument if needed)
            $redirection_url = home_url("/ar1m/");

            // Loop through order items
            foreach( $order->get_items() as $item ) {
                if( in_array( $item->get_product_id(), $product_ids ) ) {
                    wp_redirect( $redirection_url );
                    exit();
                }
            }
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

You can pass the Order ID in the redirection url like:

$redirection_url = home_url("/ar1m/?order_id=$order_id");

Then you will be able to get the Order ID on your redirected page using:

if( isset($_GET['order_id']) && get_post_type($_GET['order_id']) === 'shop_order' ) {
    $order_id = absint($_GET['order_id']);
}