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?
2
Answers
The issue in your code lies in the usage of the in_array() function. The function expects the first parameter to be the search value, and the second parameter to be the array to search in. However, in your code, you have provided the search value as the second parameter and two integers as the first parameter. Here’s the corrected code:
As finally you are comparing 2 arrays, use instead
array_intersect()
, replacing this code line:with:
Now it should work for all product types, including variations.
Also to shorten the loop, you should add a
break;
below$redirection = true;
(optional).