【问题标题】:Get all categories of a custom post type获取自定义帖子类型的所有类别
【发布时间】:2016-08-05 13:19:12
【问题描述】:

我正在尝试获取自定义帖子类型的所有类别。我正在使用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(); ?>

有什么解决办法吗??

【问题讨论】:

  • 您正在尝试获取类别,但您的代码显示您获取的是帖子,而不是类别。
  • 您的自定义帖子类型分类名称是什么?

标签: php wordpress categories custom-post-type


【解决方案1】:

您可以从这里找到更多信息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】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      更多信息在这里:https://developer.wordpress.org/reference/functions/wp_list_categories/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-11
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 2015-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多