Here is an example function that you can add to your WordPress theme's functions.php file to redirect users to a thank you page after a successful purchase in WooCommerce, where the thank you page is different depending on the product category:
function custom_woo_thank_you_redirect( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item['product_id'];
$product = wc_get_product( $product_id );
$terms = get_the_terms( $product_id, 'product_cat' );
// Check if the product belongs to a certain category
if ( ! empty( $terms ) && is_array( $terms ) ) {
$term = array_shift( $terms );
if ( 'category_1' === $term->slug ) {
wp_redirect( 'https://www.example.com/thank-you-category-1/' );
exit;
} elseif ( 'category_2' === $term->slug ) {
wp_redirect( 'https://www.example.com/thank-you-category-2/' );
exit;
}
}
}
wp_redirect( 'https://www.example.com/default-thank-you/' );
exit;
}
add_action( 'woocommerce_thankyou', 'custom_woo_thank_you_redirect' );
In this example, the function custom_woo_thank_you_redirect() is hooked into the woocommerce_thankyou action, which is triggered after a successful purchase. The function retrieves the order details, loops through the items in the order, and checks the product category. If the product belongs to a certain category, the user is redirected to a specific thank you page. If no category matches, the user is redirected to a default thank you page.
Note that you'll need to replace the URLs in the wp_redirect() function with the actual URLs of your thank you pages. Additionally, you'll need to replace "category_1" and "category_2" with the actual slugs of the categories that you want to target.

