I am trying to get the parent category and child category from the current post.
The custom post type is called assortiment
and the custom taxonomy is called assortiment-categorie
.
We have a product called SL524CB – 500kg
with parent category Test
and subcategory (of Test
) test b
.
Now I did make a loop which outputs the sub category name (test b
) but we also want the parent category name (Test
).
To output them we want 2 variables like $parent_category
and $subcategory
so we can output them in our template.
This is the loop we are using right now:
<?php
global $post;
$terms = wp_get_object_terms( $post->ID, 'assortiment-categorie', array('fields'=>'names'));
$term_id = array_pop( $terms ); //gets the last ID in the array
echo $term_id;
?>
If someone could help me that would be great, thanks for your time already!
2
Answers
There is a multitude of ways we can achieve that.
@Chris Haas comment is one way to do it. Me, I prefer using an alternative way.
Regarding parents, we can use
get_term_parents_list()
which will return a specific term’s parents.Regarding children, we can use
get_term_children()
which will return a specific term’s children.Use get_the_terms().
If you print
$categories
then you will have an output like below. where you can determine that$term
isparent
orchild
.Try this below code.