38
Once a customer places an order, you might want to know if such order contains a given product ID. you can use this for tracking purposes, redirect to a custom thank you page or run your custom functions.
Either way, checking this is quite simple thanks to the “woocommerce_thankyou” hook which runs on the order received page. Enjoy!
PHP Snippet: Check if Order Contains Product ID
/**
* @snippet WooCommerce: Check if Product ID is in the Order
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WooCommerce 3.8
* @donate $9 https://tutoraspire.com
*/
add_action( 'woocommerce_thankyou', 'tutoraspire_check_order_product_id' );
function tutoraspire_check_order_product_id( $order_id ){
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ( $items as $item_id => $item ) {
$product_id = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
if ( $product_id === XYZ ) {
// do something
}
}
}