我想从每个类别中获取3个帖子(如果存在),并且仅执行一次查询以获取所有帖子。
例如,如果我有3个类别,那么我希望从所有类别中总共获得9个帖子。
以下是我使用循环执行多个查询的方法:
display:inline-block
我尝试过:
$query = new WP_Query;
foreach ( $cats as $cat ) :
$query->query( array(
'cat' => $cat->term_id,
'posts_per_page' => 3,
'no_found_rows' => true,
'ignore_sticky_posts' => true,
));
如果每个类别或所有现有类别中都存在3个帖子,我将无法弄清楚。
结果,我从第一类只得到3个帖子
答案 0 :(得分:1)
尝试以下
$args = array(
'cat' => array(1,2,3),
'order' => 'ASC',
'showposts' => 3
);
query_posts($args);
答案 1 :(得分:0)
<?php
$cat_args = array (
'orderby' => 'name',
'order' => 'ASC',
);
$threecategories = get_categories( $cat_args );
foreach ( $threecategories as $threecategory ) {
echo '<a href="' . esc_url( get_category_link( $threecategory->term_id ) ) . '">' . $threecategory->name . '</a>';
$post_args = array(
'posts_per_page' => 3,
'cat' => $threecategory->cat_ID
);
$threeposts = query_posts( $post_args );
while(have_posts()) : the_post();
echo '<a href="' . esc_url( get_the_permalink() ) . '">' . get_the_title(). '</a>';
endwhile;
}
wp_query_reset();
也许这会对您有帮助