phpwordpresswoocommercecategories

WooCommerce - Display sub-category from specific category parent in order email


So I have this weird request about displaying what sub-categories a product is assigned to in the order emails being sent out upon order confirmation in WooCommerce - however I would only like to show the categories from a specific category parent.

You see, I have two main-categories in WooCommerce, one being Brands and the other being Categories. I'd like to only display the sub-categories being assigned to a specific product under the Brands category. In my case the Brands category (parent) has the ID 15.

The code snippet that I have currently tested and is confirmed working is this

function modfuel_woocommerce_before_order_add_cat($name, $item){

   $product_id = $item['product_id'];

   $_product = wc_get_product( $product_id );
   $htmlStr = "";
   $cats = "";
   $terms = get_the_terms( $product_id, 'product_cat' );

   $count = 0;
   foreach ( $terms as $term) {
    $count++;

    if($count > 1){
      $cats .= $term->name;
    }
    else{
      $cats .= $term->name . ',';
    }

   }

   $cats = rtrim($cats,',');

   $htmlStr .= $_product->get_title();

   $htmlStr .= "<p>Category: " . $cats . "</p>";

   return $htmlStr;
}

add_filter('woocommerce_order_item_name','modfuel_woocommerce_before_order_add_cat', 10, 2);

Any way someone here knows what I could add in the code above in order to get what I need?

Thanks!


Solution

  • If I understand your code right you now have all the categories in $terms and want to skip all the terms that aren't children of brand.

    You could simply skip the terms that don't have this parent. your code would than look like this:

    function modfuel_woocommerce_before_order_add_cat($name, $item){
    
       $product_id = $item['product_id'];
    
       $_product = wc_get_product( $product_id );
       $htmlStr = "";
       $cats = "";
       $terms = get_the_terms( $product_id, 'product_cat' );
    
       $count = 0;
       foreach ( $terms as $term) {
        if ($term->parent != 15) continue;
        $count++;
    
        if($count > 1){
          $cats .= $term->name;
        }
        else{
          $cats .= $term->name . ',';
        }
    
       }
    
       $cats = rtrim($cats,',');
    
       $htmlStr .= $_product->get_title();
    
       $htmlStr .= "<p>Category: " . $cats . "</p>";
    
       return $htmlStr;
    }
    
    add_filter('woocommerce_order_item_name','modfuel_woocommerce_before_order_add_cat', 10, 2);
    

    I added the if ($term->parent != 15) continue; code to skip the term if it isn't a direct child of Brand (ID: 15).