I use wooCommerce theme and this my working redirect after checkout per product code :
add_action( 'woocommerce_thankyou', 'redirect_product_based', 1 );
function redirect_product_based ( $order_id ){
$order = wc_get_order( $order_id );
foreach( $order->get_items() as $item ) {
// Add whatever product id you want below here
if ( $item['product_id'] == 3531 ) {
// URL
wp_redirect( 'www...' );
}
if ( $item['product_id'] == 35 ) {
// URL
wp_redirect( 'www....' );
}
}
}
Now i want code working for multiple products like :
add_action( 'woocommerce_thankyou', 'redirect_product_based', 1 );
function redirect_product_based ( $order_id ){
$order = wc_get_order( $order_id );
foreach( $order->get_items() as $item ) {
// Add whatever product id you want below here
if ( $item['product_id'] == 331, 332, ... ) {
// URL
wp_redirect( 'www...' );
}
if ( $item['product_id'] == 35, 36, ... ) {
// URL
wp_redirect( 'www....' );
}
}
}
Any help with this to apply for multiple products please.
CodePudding user response:
The easiest way to achieve this with as little modification to your working code as possible would be to use in_array()
.
Also, please note the use of exit;
after wp_redirect
. You can see why I added it on this post and in the docs:
Note: wp_redirect() does not exit automatically, and should almost always be followed by a call to exit;
Furthermore, if you want to make sure that you always redirect to a page on an allowed host, you should have a look at wp_safe_redirect
and replace your wp_redirect
calls
add_action( 'woocommerce_thankyou', 'redirect_product_based', 1 );
function redirect_product_based ( $order_id ){
$order = wc_get_order( $order_id );
foreach( $order->get_items() as $item ) {
// Add whatever product id you want below here
if ( in_array($item['product_id'], array(331, 332)) ) {
// URL
wp_redirect( 'www...' );
exit;
}
if ( in_array($item['product_id'], array(35, 36)) ) {
// URL
wp_redirect( 'www....' );
exit;
}
}
}