获取自定义帖子类型的所有类别


Get all categories of a custom post type

我正在尝试获取自定义帖子类型的所有类别。我正在使用get_the_category();函数来检索类别。但是,如果我有3个帖子和1个类别,该类别会重复3次:o。

我的代码是

<?php 
    query_posts( array( 'post_type' => 'member', 'showposts' => 8 ) );
    if ( have_posts() ) : while ( have_posts() ) : the_post();
        $categories = get_the_category();
            foreach ( $categories as $category ) { 
        echo $category->name, ' '; 
    }             
?>
<?php endwhile; endif; wp_reset_query(); ?>

有什么解决方案吗??

您可以从这里找到更多信息REFERENCE FOR get_terms

<?php
$taxonomy = 'YOUR TEXONOMY NAME';
$terms = get_terms($taxonomy);
if ( $terms && !is_wp_error( $terms ) ) :
?>
    <ul>
        <?php foreach ( $terms as $term ) { ?>
            <li><a href="<?php echo get_term_link($term->slug, $taxonomy); ?>"><?php echo $term->name; ?></a></li>
        <?php } ?>
    </ul>
<?php endif;?>

尝试这种方式只获得自定义后的类别

<?php 
$category = get_terms('category');//custom category name 
foreach ($category as $catVal) {
    echo '<h2>'.$catVal->name.'</h2>'; 
 }
?>

你正在循环浏览帖子,你尝试过吗?

<?php
wp_list_categories( array(
    'taxonomy' => 'category', // CHANGE HERE TO YOUR TAXONOMY
) );
?>

更多信息请点击此处:https://developer.wordpress.org/reference/functions/wp_list_categories/