A customer recently required a way to redirect users to a custom thank-you page for a specific product variation. Below, you will find three useful code snippets to achieve this redirection after an order is placed.
- The first snippet redirects all orders.
- The second snippet redirects customers if a single variation ID matches.
- The third snippet allows for redirection when you need to specify multiple variation IDs.
Redirect All Orders
add_action( 'woocommerce_thankyou', 'woo_custom_thank_you');
function woo_custom_thank_you( $order_id ){
$order = wc_get_order( $order_id );
$url = 'https://yourwebsite.com/thank-you-page';
if ( ! $order->has_status( 'failed' ) ) {
wp_safe_redirect( $url );
exit;
}
}
Redirect A Single Product Variation ID
add_action( 'woocommerce_thankyou', 'redirect_one_variation', 1 );
function redirect_one_variation( $order_id ) {
$order = wc_get_order( $order_id );
foreach( $order->get_items() as $item ) {
// Add Your Variation ID Here
if ( isset( $item['variation_id'] ) && $item['variation_id'] == 1005 ) {
// Set Custom Page URL Here
$redirect_url = 'https://yourwebsite.com/thank-you-page';
wp_safe_redirect( esc_url( $redirect_url ) );
exit;
}
}
}
Redirect Multiple Variation IDs
add_action( 'woocommerce_thankyou', 'redirect_multiple_variations', 1 );
function redirect_multiple_variations( $order_id ) {
$order = wc_get_order( $order_id );
// Array of Variation IDs to redirect
$variation_ids_to_redirect = array( 10719, 10721, 10723, 10725 );
foreach( $order->get_items() as $item ) {
if ( isset( $item['variation_id'] ) && in_array( $item['variation_id'], $variation_ids_to_redirect ) ) {
// Set Custom Page URL Here
$redirect_url = esc_url( 'https://yourwebsite.com/thank-you-page' );
wp_safe_redirect( $redirect_url );
exit(); // Exit after the redirect
}
}
}
Please add the above snippets to your child theme’s functions.php
file or to a custom snippets plugin.