Last active
October 7, 2023 21:34
-
-
Save sectsect/306d2b2fc1f3d904126ffef22ed5e888 to your computer and use it in GitHub Desktop.
Wordpress: Get the Deepest Terms. Supports Term order and Multiple Categories in Deepest hierarchy.
This file contains 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 | |
function get_the_terms_deepest($taxonomies, $term_order = false) { | |
$categories = get_the_terms(get_the_ID(), $taxonomies); // get all product cats for the current post | |
if($categories && !is_wp_error($categories)){ // wrapper to hide any errors from top level categories or products without category | |
if(count($categories) == 1){ // Case: Select only Category of Top Level. (Required: Activate Plugin Parent Category Toggler) | |
$return = $categories; | |
}elseif(count($categories) > 1){ | |
$return = array(); | |
foreach($categories as $category){ // loop through each cat | |
$children = get_categories(array('taxonomy' => $taxonomies, 'parent' => $category->term_id)); // get the children (if any) of the current cat | |
if(count($children) == 0){ | |
array_push($return, $category); | |
} | |
} | |
// term_order | |
if($return && $term_order){ | |
$orderarray = array(); | |
foreach((array)$return as $value){ | |
$orderarray[$value->term_order] = $value; | |
} | |
if($term_order == "ASC"){ | |
ksort($orderarray); | |
}elseif($term_order == "DESC"){ | |
krsort($orderarray); | |
} | |
$return = $orderarray; | |
} | |
}else{ | |
$return = false; | |
} | |
return $return; | |
} | |
} | |
?> |
This file contains 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 | |
$terms = get_the_terms_deepest("category", "ASC"); // The 2nd parameter is for 'term_order'. This is useful when multiple terms are returned. Available value: false or "ASC" or "DESC". | |
if($terms && !is_wp_error( $terms )){ | |
$termnames = array(); | |
foreach($terms as $term){ | |
array_push($termnames, $term->name); // term_id / name / slug etc.. | |
} | |
echo implode(",", $termnames); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment