Reputation: 85
I'm working on an index page that lists all posts for a custom post type. I've been listing the categories for each post using <?php echo strip_tags(get_the_term_list( $post->ID, 'genre', ' ',' • ')); ?>
.
We need to add sub-categories but I don't want these to display on the index page - just the parent category. Have tried using get_term_parents_list
and a few other examples from here but can't get anything working.
Can anyone help?
Upvotes: 0
Views: 219
Reputation: 2088
You can use get_the_terms
filter to change the terms to return.
add_filter('get_the_terms', 'only_parent_genre', 10, 3);
function only_parent_genre($terms, $post_id, $taxonomy) {
// TODO for you : Add condition to heck if you are not on your custom index too.
if(is_admin() || $taxonomy !== 'genre') {
return $terms;
}
// Loop over terms and if parent is something different than 0, it means that's its a child term
foreach($terms as $key => $term) {
if($term->parent !== 0) {
unset($terms[$key]);
}
}
return $terms;
}
Upvotes: 1