We already saw how to check if a product category is in the cart, if a product ID is in the cart, and if a product ID is in the order… now it’s time to complete the series with the latest addition!

For this client, the scope was to do something on the “Thank You” page if a certain product category was purchased. For example, echo a “Thank you for becoming a member!” image in case the category “membership” was in the order.

Here’s the snippet, together with PHP comments so that you can understand how this is done. Enjoy!

Check if Product Category is in the WooCommerce Order

PHP Snippet: Check if Product Category is in the Order – WooCommerce

/**
 * @snippet       Check if Product Category is in the Order
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    Woo 4.0
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'woocommerce_thankyou', 'bbloomer_custom_woocommerce_auto_complete_order', 5 );
 
function bbloomer_custom_woocommerce_auto_complete_order( $order_id ) { 
 
   // 1. Get order object
   $order = wc_get_order( $order_id );
 
   // 2. Initialize $cat_in_order variable
   $cat_in_order = false;
 
   // 3. Get order items and loop through them...
   // ... if product in category, edit $cat_in_order
   $items = $order->get_items(); 
     
   foreach ( $items as $item ) {      
      $product_id = $item->get_product_id();  
      if ( has_term( 'memberships', 'product_cat', $product_id ) ) {
         $cat_in_order = true;
         break;
      }
   }
 
   // 4. Echo image only if $cat_in_order == true   
   if ( $cat_in_order ) {
      echo '<p><img src="https://....."></p>';     
   }
   
}
Share:

Leave a Reply