首页 > 解决方案 > 循环显示自定义帖子类型类别(术语)

问题描述

我正在使用以下代码从自定义帖子类型加载所有帖子,在这个循环中我显示一个标题,但我也想显示与这个特定帖子相关的类别(术语),但我似乎无法制作这行得通

环形:

<?php $args = array( 'post_type' => 'fotoalbum', 'showposts'=> '-1' ); $the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php $i=1; ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if($i==1 || $i%3==1) echo '<div class="row">' ;?>

    <div class="col-md-4">
        <a href="<?php the_permalink(); ?>"><?php the_title();?></a><br/>
        ! HERE I WANT THIS POSTS CATEGORY !
    </div>

<?php if($i%3==0) echo '</div>';?>
<?php $i++; endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>

我试过了:

<?php echo $term->name; ?>

标签: wordpresscustom-post-typetaxonomy-terms

解决方案


您需要使用 get_the_terms() 来获取类别,您可以通过以下代码获得它...您需要将第二个参数放在自定义帖子类型的类别 slug 中,您可以参考此链接https://developer.wordpress.org/reference/函数/get_the_terms/



    <?php $args = array( 'post_type' => 'fotoalbum', 'showposts'=> '-1' ); $the_query = new WP_Query( $args ); ?>
    <?php if ( $the_query->have_posts() ) : ?>
    <?php $i=1; ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <?php if($i==1 || $i%3==1) echo '<div class="row">' ;?>
    <div class="col-md-4">
        <a href="<?php the_permalink(); ?>"><?php the_title();?></a><br/>
        ! HERE I WANT THIS POSTS CATEGORY !
        <?php 
        $terms = get_the_terms( get_the_ID(), 'category-slug' ); // second argument is category slug of custom post-type
        if(!empty($terms)){
        foreach($terms as $term){
            echo $term->name.'<br>';
        }
        }
        ?>
    </div>

    <?php if($i%3==0) echo '</div>';?>
    <?php $i++; endwhile; ?>
    <?php wp_reset_postdata(); ?>
    <?php endif; ?>


推荐阅读