Created
March 4, 2020 20:22
-
-
Save cristianstan/af7745b67b2c8f09c89bded1cbcae29c to your computer and use it in GitHub Desktop.
Get Deepest category id of a product (WooCommerce)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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