In some cases, you may wish to redirect users to a different thank you page based on a product purchased in the order. Perhaps there’s specific information you need to tell the customer about and the only practical way is through a custom page. This guides shows you how you can redirect users to a custom thank you page based on a product purchased in the order. You will need the custom thank you page URL and appropriate product ID ready.
/**
* Snippet Name: Redirect users to a custom WooCommerce thank you page based on a product bought in the order.
* Snippet Author: ecommercehints.com
*/
add_action( 'template_redirect', 'ecommercehints_product_dependant_thank_you_page' );
function ecommercehints_product_dependant_thank_you_page(){
if( !is_wc_endpoint_url( 'order-received' ) || empty( $_GET['key'] ) ) {
return;
}
$order_id = wc_get_order_id_by_order_key( $_GET['key'] );
$order = wc_get_order( $order_id );
foreach( $order->get_items() as $item ) {
if( $item['product_id'] == 123 ) { // product id here
wp_redirect( 'YOUR URL' ); // your custom thank you page url here
exit;
}
}
}