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

时间:2016-04-14 06:35:15

标签: php wordpress categories 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(); ?>

有没有解决方案?

3 个答案:

答案 0 :(得分:2)

尝试这种方式只获取自定义帖子的类别

<?php 

$category = get_terms('category');//custom category name 

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

答案 1 :(得分:2)

您可以在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;?>

答案 2 :(得分:0)

你正在浏览帖子,你试过这个吗?

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

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