最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - How to show the category of custom taxonomy

programmeradmin0浏览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.

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
  • 1 The underlying function used by has_category() is has_term(), you can use it for any taxonomies including custom ones. – Ivan Shatsky Commented Nov 24, 2020 at 10:43
  • Thanks! Will try – Shark Deng Commented Nov 24, 2020 at 10:45
Add a comment  | 

2 Answers 2

Reset to default 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', '', ', ');

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.

发布评论

评论列表(0)

  1. 暂无评论