Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cristianstan/af7745b67b2c8f09c89bded1cbcae29c to your computer and use it in GitHub Desktop.
Save cristianstan/af7745b67b2c8f09c89bded1cbcae29c to your computer and use it in GitHub Desktop.
Get Deepest category id of a product (WooCommerce)
<?php
/**
*
* Get deepest product category woocommerce
* @param $product_id is the id of a product
*
*/
function prefix_get_deepest_product_category($product_id = ''){
// get all product cats for the current post
$categories = get_the_terms( $product_id, 'product_cat' );
// wrapper to hide any errors from top level categories or products without category
if ( $categories && ! is_wp_error( $category ) ) :
// loop through each cat
foreach($categories as $category) :
// get the children (if any) of the current cat
$children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
if ( count($children) == 0 ) {
// if no children, then echo the category name.
return $category->term_id;
}
endforeach;
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment