2016-07-25 122 views
0

我想创建一个循环,显示自定义帖子类型的类别(作为按钮)的列表。我有一个循环工作,但它循环所有的自定义帖子并显示每个类别。所以现在如果我有两个相同类别的帖子,它会显示相同的类别两次。此外,我需要回应自定义类为我的同位素过滤器工作。Wordpress循环显示重复的类别

这是我的代码:

  <?php 
      $args = array( 
       'post_type' => 'ondernemers', 
       'posts_per_page' => 10 
       ); 

      $loop = new WP_Query($args); 
      while ($loop->have_posts()) : $loop->the_post(); 

      $categories = get_the_category($post->ID, 'taxonomy'); 
      foreach($categories as $category) { 
       echo '<button class="button" data-filter=".' . $category->slug . ' "><div class="button-img-' . $category->slug . '"></div>' . $category->name . '</button>'; 
      } 

      endwhile; 
      ?> 

有没有一种方法,使循环打印每个类别只有一次,而不是一次每次它只是每一个独特的帖子?

回答

1

使用以下代码检索自定义帖子类型的类别名称。

<?php 
    $args = array(
     'type'      => 'post', /* custom post type name */ 
     'parent'     => '', 
     'orderby'     => 'id', 
     'order'     => 'ASC', 
     'hide_empty'    => 1, 
     'hierarchical'    => 1, 
     'taxonomy'     => 'category' /* custom post type texonomy name */ 
    ); 
    $cats = get_categories($args); 
    foreach ($cats as $cat) {   
     $cat_id= $cat->term_id; 
     $cat_name= $cat->name; ?> 
     <h3><?php echo '<a href="' . get_category_link($cat_id) . '">'.$cat->name.'</a>'; ?></h3>  
    <?php } ?> 
1

您可以尝试此操作来检索自定义帖子类型分类列表。

<?php 
$categories = get_the_terms($post->ID, 'taxonomy_name'); 
foreach($categories as $category): ?> 
    <button data-filter="<?php echo $category->slug; ?>"> 
    <?php echo $category->name; ?> 
    </button> 
<?php endforeach; ?> 

修改为您的需要。