0

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.

2
  • 1
    The underlying function used by has_category() is has_term(), you can use it for any taxonomies including custom ones. Nov 24 '20 at 10:43
  • Thanks! Will try
    – Shark Deng
    Nov 24 '20 at 10:45
1

Usually 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', '', ', ');
1
  • Thank you, will try this.
    – Shark Deng
    Nov 24 '20 at 11:06
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.