我有一個名爲news的類別和其中的許多子類別。 我想要做的是從每個子類別(包括類別標題,帖子標題,附件圖像)中只獲得1個帖子(最新)。 有沒有建議朋友?如何從wordpress中的每個類別獲得1個帖子
5
A
回答
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
數小時後並感謝我們的同伴都在全球範圍內,我已經能夠修改主查詢,所以我們甚至都不需要去模板,生成新的查詢和循環..
// 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');
相關問題
- 1. 從兩個類別獲取Wordpress帖子
- 2. 從每個類別中獲取最新帖子,並在wordpress中添加帖子
- 3. 獲取最新的每個類別的5個WordPress帖子
- 4. 如何在WordPress中顯示每個類別的帖子數量?
- 5. WordPress從循環以外的X類別獲得每個帖子的1個附件
- 6. Wordpress-如何顯示每個帖子的鏈接類別?
- 7. WordPress - 通過自定義帖子類型和類別獲取帖子,每個類別自動包含在DIV中
- 8. 從帖子ID獲取Wordpress類別ID
- 9. 限制wordpress的每個類別和子項的帖子數
- 10. 如何通過類別與圖像獲得WordPress的帖子
- 11. 如何獲得熱門帖子來自WordPress的選定類別?
- 12. 顯示Wordpress中循環內每個帖子的類別名稱
- 13. 如何獲得類別頁面的子類別和帖子?
- 14. MySQL查詢從每個類別獲得1個結果LEFT JOIN
- 15. 每n個帖子添加一個特定類別的帖子
- 16. 如何在wordpress中顯示自定義帖子類型的每個類別的最新帖子
- 17. 如何從wordpress頁面獲得帖子meta到另一個?
- 18. 無法更改WordPress中的每個帖子的帖子帖子類型查詢
- 19. 如何在Wordpress中列出兩個類別的常見帖子?
- 20. 木材Wordpress顯示每個類別的帖子
- 21. 單個Wordpress頁面中的兩個帖子類型/類別?
- 22. 如何從Wordpress的父類別中排除子帖子?
- 23. 在DIV中包裹每個1到4個WordPress帖子
- 24. 如何通過JavaScript從父類別獲取每個子類別?
- 25. 獲得每個帖子的評論
- 26. WordPress的:按類別獲取帖子
- 27. WordPress獲取所有類別的帖子
- 28. 從Wordpress中排除單個類別的所有帖子結果
- 29. wordpress類別:如何找到帖子的最後一個子類別
- 30. WordPress的類別和帖子
這是你的第六個問題,你仍然沒有接受任何以前的答案。請這樣做,如果有任何有用的答案,這將在這裏提高你的業力:) – FelipeAls 2010-07-17 21:08:01