Thank you page redirection for specific product ID in WooCommerce Order items

Viewed 298

One of my products requires a specific thank you page.

Here's the code I have. The Product ID is 1813 and the category is gimnasio-mental. I don't really need, nor want to include the category in this code, so if it can be simplified, even better!

add_action( 'template_redirect', 'wc_custom_redirect_after_purchase' );
function wc_custom_redirect_after_purchase() {
    if ( ! is_wc_endpoint_url( 'order-received' ) ) return;

    // Define the product IDs in this array
    $product_ids = array( 1813 ); // or an empty array if not used
    // Define the product categories (can be IDs, slugs or names)
    $product_categories = array( 'gimnasio-mental' ); // or an empty array if not used
    $redirection = false;

    global $wp;
    $order_id =  intval( str_replace( 'checkout/order-received/', '', $wp->request ) ); // Order ID
    $order = wc_get_order( $order_id ); // Get an instance of the WC_Order Object

    // Iterating through order items and finding targeted products
    foreach( $order->get_items() as $item ){
        if( in_array( $item->get_product_id(), $product_ids ) || has_term( $product_categories, 'product_cat', $item->get_product_id() ) ) {
            $redirection = true;
            break;
        }
    }

    // Make the custom redirection when a targeted product has been found in the order
    if( $redirection ){
        wp_redirect( home_url( '/gracias-gimnasio-mental/' ) );
        exit;
    }
}
1 Answers

You could use the woocommerce_thankyou action hook against template_redirect

Explanation via comment tags added in the code

function action_woocommerce_thankyou( $order_id ) {
    if( ! $order_id ) {
        return;
    }

    // Instannce of the WC_Order Object
    $order = wc_get_order( $order_id ); 

    // Is a WC_Order
    if ( is_a( $order, 'WC_Order' ) ) {
        // False
        $redirection = false;
        
        // Loop through order items
        foreach ( $order->get_items() as $item_key => $item ) {
            // Product ID(s)
            $product_ids = array( $item->get_product_id(), $item->get_variation_id() );
            
            // Product ID in array
            if ( in_array( 1813, $product_ids ) ) {
                $redirection = true;
            }
        }
    }

    // Make the custom redirection when a targeted product has been found in the order
    if ( $redirection ) {
        wp_safe_redirect( home_url( '/gracias-gimnasio-mental/' ) );
        exit;
    }
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );
Related