2010-07-16 127 views
5

我有一個名爲news的類別和其中的許多子類別。 我想要做的是從每個子類別(包括類別標題,帖子標題,附件圖像)中只獲得1個帖子(最新)。 有沒有建議朋友?如何從wordpress中的每個類別獲得1個帖子

+3

這是你的第六個問題,你仍然沒有接受任何以前的答案。請這樣做,如果有任何有用的答案,這將在這裏提高你的業力:) – FelipeAls 2010-07-17 21:08:01

回答

11
<?php 

$news_cat_ID = get_cat_ID('News'); 
$news_cats = get_categories("parent=$news_cat_ID"); 
$news_query = new WP_Query; 

foreach ($news_cats as $news_cat) : 
    $news_query->query(array(
     'cat'     => $news_cat->term_id, 
     'posts_per_page'  => 1, 
     'no_found_rows'  => true, 
     'ignore_sticky_posts' => true, 
    )); 

    ?> 

    <h2><?php echo esc_html($news_cat->name) ?></h2> 

    <?php while ($news_query->have_posts()) : $news_query->the_post() ?> 

      <div class="post"> 
       <?php the_title() ?> 
       <!-- do whatever you else you want that you can do in a normal loop --> 
      </div> 

    <?php endwhile ?> 

<?php endforeach ?> 
+0

謝謝你THEDeadMedic。它的工作,你能幫助我另一個。 (擴展名相同的代碼) 我該如何顯示那些有圖像附件並按日期排列 – sonill 2010-07-18 05:37:42

+0

謝謝你的帖子,它正在尋找完全相同的東西! +1 – Tarun 2011-07-26 10:16:05

+0

爲我節省了大量的時間,謝謝@TheDeadMedic – 2014-02-17 04:41:32

0

數小時後並感謝我們的同伴都在全球範圍內,我已經能夠修改主查詢,所以我們甚至都不需要去模板,生成新的查詢和循環..

// My function to modify the main query object 
function grouped_by_taxonomy_main_query($query) { 

    if ($query->is_home() && $query->is_main_query()) { // Run only on the homepage 

     $post_ids = array(); 

     $terms = get_terms('formato'); 

     foreach ($terms as $term) { 
      $post_ids = array_merge($post_ids, get_posts(array( 
       'posts_per_page' => 4, // as you wish... 
       'post_type' => 'video', // If needed... Default is posts 
       'fields' => 'ids', // we only want the ids to use later in 'post__in' 
       'tax_query' => array(array('taxonomy' => $term->taxonomy, 'field' => 'term_id', 'terms' => $term->term_id,)))) // getting posts in the current term 
      ); 
     } 

     $query->query_vars['post_type'] = 'video'; // Again, if needed... Default is posts 
     $query->query_vars['posts_per_page'] = 16; // If needed... 
     $query->query_vars['post__in'] = $post_ids; // Filtering with the post ids we've obtained above 
     $query->query_vars['orderby'] = 'post__in'; // Here we keep the order we generated in the terms loop 
     $query->query_vars['ignore_sticky_posts'] = 1; // If you dont want your sticky posts to change the order 

    } 
} 

// Hook my above function to the pre_get_posts action 
add_action('pre_get_posts', 'grouped_by_taxonomy_main_query'); 
相關問題