2016-06-07 84 views
0

我必須從每個類別顯示2個職位。下面的代碼獲取屬於每個類別的所有帖子。我的結構是基於標籤的。我附上了我設計的圖像。我的標籤包含「所有的(顯示所有崗位)」,「症狀(表明相關症狀職位只」等,點擊每個選項卡顯示相關的帖子。 enter image description here如何在wordpress中只顯示每個類別的兩篇文章?

<?php $recent = new WP_Query("post_type=post&posts_per_page=-1&orderby=date&order=DESC"); 
       $count=0;       
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
        while($recent->have_posts()) : $recent->the_post(); ?> 
        <?php $c = get_the_category(); 
        $cat = $c[0]->cat_name; 
        $slug = $c[0]->category_nicename; 
        ?> 
        <div class="element-item transition <?php echo $slug;?>" data-category="<?php echo $slug;?>"> 
         <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> 
          <div class="descrip"> 
           <h2><?php the_title(); ?></h2> 
          </div> 
         </a> 
        </div> 
       <?php endwhile; wp_reset_postdata(); ?> 

[![請在此輸入圖片說明] [2] [2]

任何幫助,將不勝感激

回答

2

嘗試這樣

<?php 

    $cat_args = array(
     'orderby'  => 'date', 
     'order'  => 'DESC', 
     'child_of'  => 0, 
     'parent'  => '', 
     'type'   => 'post', 
     'hide_empty' => true, 
     'taxonomy'  => 'category', 
    ); 

    $categories = get_categories($cat_args); 

    foreach ($categories as $category) { 

     $query_args = array(
      'post_type'  => 'post', 
      'category_name' => $category->slug, 
      'posts_per_page' => 2, 
      'orderby'  => 'date', 
      'order'   => 'DESC' 
     ); 

     $recent = new WP_Query($query_args); 

     while($recent->have_posts()) : 
      $recent->the_post(); 
     ?> 
     <div class="element-item transition <?php echo $category->slug;?>" data-category="<?php echo $category->slug;?>"> 
      <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> 
       <div class="descrip"> 
        <h2><?php the_title(); ?></h2> 
       </div> 
      </a> 
     </div> 
     <?php endwhile; 
    } 
    wp_reset_postdata(); 
?> 

首先列出所有的類別,然後在foreach循環遍歷每個,並且只查詢2個最近的。

請注意,您可以通過這種方式列出任何分類。我只是把

'taxonomy'  => 'category', 

但這可以是分配給您的自定義帖子類型的分類,例如。論據

列表看起來有點像這樣:

$args = array(
    'type'      => 'post', 
    'child_of'     => 0, 
    'parent'     => '', 
    'orderby'     => 'name', 
    'order'     => 'ASC', 
    'hide_empty'    => 1, 
    'hierarchical'    => 1, 
    'exclude'     => '', 
    'include'     => '', 
    'number'     => '', 
    'taxonomy'     => 'category', 
    'pad_counts'    => false 
); 

希望這有助於。

相關問題