I want to display as links, the parent categories (but not the grandfather categories), only when I am viewing the last/deepest category. To be more expressive, when I browse the categories, I have some code that gets the subcategories/children of the current category I am in. The code is this
function sub_cats( $args = array() ) {
$terms = get_terms([
'taxonomy' => get_queried_object()->taxonomy,
'parent' => get_queried_object_id(),
]);
foreach ( $terms as $term) {
echo '<li>';
echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';
echo '<li>';
}
}
Since I reach the last/deepest category/child of each category tree, I get no other categories to display.
Now I am asked to display as links, only the direct parent categories (not the grandfathers) of the last/deepest category and only then.
What I figured out is, to check if there are children in the current category and if they do, fire up the above code. If not then get the parent category. But here is where I blow it all up because in return I get as results all attributes and categories in my database.
//Get current category
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
//If this category has children then get me the children
if($children) {
$terms = get_terms([
'taxonomy' => get_queried_object()->taxonomy,
'parent' => get_queried_object_id(),
]);
foreach ( $terms as $term) {
echo '<li>';
echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';
echo '<li>';
}
} else { //ELSE get me only the parent category -> HERE IS MY PROBLEM
$caterms = get_terms( $product->ID, 'product_cat' );
foreach ($caterms as $category) {
if($category->parent == 0){
echo '<li>';
echo '<a href="' . get_term_link( $category ) . '">' . $category->name . '</a>';
echo '<li>';
}
}
}
Please help
2
Answers
This function gets in li tags, all product categories, from the very first/top-level categories, to the very last/bottom-level categories. Then, when you browse to the bottom/deepest categories, you get all same-(last/deepest)level categories. So, the category tree, does not vanish when you get to those deep/last categories.
Special thanks to Panos(VG) and @Frits
You could just make use of the
parent
property inside yourterm
object and grab the term directly usingget_term_by()
.