Get Product Category From Product Id Or Order Id

get product category from product id or order id

Get Product Category From Product Id Or Order Id

 |   |  0
WooCommerce WordPress

Here, I wish to share how to get product category from product id or order id in WooCommerce / WordPress.

Here it is the code, chill …

Code:

function getProductCategory($order_id='' , $product_id ='') {
if(!empty($order_id)) {
  $order = wc_get_order( $order_id );
  $items = $order->get_items();
  foreach ( $items as $item ) {
    $product_id = $item->get_product_id();
    $terms = get_the_terms ( $product_id, 'product_cat' );
    if(count($terms) == 1) {
      $cat = $terms[0]->name;
      return $cat;
    }
    foreach ( $terms as $term ) {
      $cat_name[] = $term->name;
    }
  }
  return $cat_name;
}

if(!empty($product_id)) {
  $terms = get_the_terms ( $product_id, 'product_cat' );
  foreach ( $terms as $term ) {
     $cat_name = $term->name;
  }
  return $cat_name;
}
}

Thanks ..


0 Claps

Show your love in the form of Claps and Comments...

Comments...

No comments found. Leave your reply here.