I have a code that works great to redirect to a custom Thank You page after purchasing any product.
add_action( 'woocommerce_thankyou', 'updated_redirectcustom');
function updated_redirectcustom( $order_id ){
$order = wc_get_order( $order_id );
$url = '/thank-you/';
if ( ! $order->has_status( 'failed' ) ) {
wp_safe_redirect( $url );
exit;
}
}
I decided to implement a custom redirect to another page for a couple of specific product variations, but, unfortunately, the code that I changed does not work and all orders are still redirected to the /thank-you/ URL:
add_action( 'woocommerce_thankyou', 'updated_redirectcustom');
function updated_redirectcustom( $order_id ){
$order = wc_get_order( $order_id );
$url = '/thank-you/';
if ( ! $order->has_status( 'failed' ) ) {
wp_safe_redirect( $url );
exit;
}
if( ! $order_id ) {
return;
}
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( 12345, 123456, $product_ids ) ) {
$redirection = true;
}
}
}
if ( $redirection ) {
wp_safe_redirect( home_url( '/thank-you-2/' ) );
exit;
}
}
Where am I wrong?
As finally you are comparing 2 arrays, use instead array_intersect()
, replacing this code line:
if ( in_array( 12345, 123456, $product_ids ) ) {
with:
if ( count( array_intersect( array(12345, 123456), $product_ids ) ) > 0 ) {
Now it should work for all product types, including variations.
Also to shorten the loop, you should add a break;
below $redirection = true;
(optional).