In the built category, we can use has_category()
and the_category()
to show if the post has category and the name of the category.
Now, I am using my custom post type and custom taxonomy. The above two functions are invalid in this case. I wonder what's the API to use here? Thank you.
In the built category, we can use has_category()
and the_category()
to show if the post has category and the name of the category.
Now, I am using my custom post type and custom taxonomy. The above two functions are invalid in this case. I wonder what's the API to use here? Thank you.
Share Improve this question asked Nov 24, 2020 at 10:21 Shark DengShark Deng 1055 bronze badges 2 |2 Answers
Reset to default 1Usually I used has_term()
and the_terms()
.
These are the examples
if( has_term('', 'genre') ){
// do something
}
the_terms( $post->ID, 'category', 'categories: ', ' / ' );
OR, I used this to get a list get_the_term_list()
for example
echo get_the_term_list($post->ID, 'category', '', ', ');
I found this working method, in case you are interested.
if ( true === $show_categories && has_category() ) {
?>
<div class="entry-categories">
<span class="screen-reader-text"><?php _e( 'Categories', 'twentytwenty' ); ?></span>
<div class="entry-categories-inner">
<?php the_category( ' ' ); ?>
</div><!-- .entry-categories-inner -->
</div><!-- .entry-categories -->
<?php
// custom post type
} else {
$post_type = get_post_type();
$category = $post_type . '_cat';
$taxonomy_names = wp_get_object_terms(get_the_ID(), $category);
if (true === $show_categories && !empty($taxonomy_names) ) {
$term = array_pop($taxonomy_names);
?>
<div>
<span><?php _e( 'Categories:', 'twentytwenty' ); ?></span>
<a href="<?php echo get_term_link( $term->slug, $category ); ?> "> <?php echo $term->name; ?> </a>
</div><!-- .entry-categories -->
<?php
}
}
And this is the example link, if you want to see the result.
has_category()
ishas_term()
, you can use it for any taxonomies including custom ones. – Ivan Shatsky Commented Nov 24, 2020 at 10:43