我需要显示两个wordpress查询的输出,如下所示。
输出示例:
query 1 - post 1
query 2 - post 1
query 1 - post 2
query 2 - post 2
query 1 - post 3
query 2 - post 3
...........
mycode:
<?php
$args_one = array(
\'cat\' => 7,
\'posts_per_page\' => 8
);
$args_two = array(
\'cat\' => 10,
\'posts_per_page\' => 8
);
$the_query_one = new WP_Query( $args_one );
if ( $the_query_one->have_posts() ) :
$num = 1;
while ( $the_query_one->have_posts() ) : $the_query_one->the_post();
if ($num % 2 == 0) {
$even .= get_template_part(\'mobile-template/loop\');
} else {
$odd .= get_template_part(\'mobile-template/loop\');
}
$num++;
endwhile;
wp_reset_postdata();
endif;
$the_query_two = new WP_Query( $args_two );
if ( $the_query_two->have_posts() ) :
$num = 1;
while ( $the_query_two->have_posts() ) : $the_query_two->the_post();
if ($num % 2 == 0) {
$even .= get_template_part(\'mobile-template/loop\');
} else {
$odd .= get_template_part(\'mobile-template/loop\');
}
$num++;
endwhile;
wp_reset_postdata();
endif;
echo $even . $odd;
?>
这段代码工作得很好,但我需要一个更好的或WP标准的方法。
最合适的回答,由SO网友:Mikhail 整理而成
为什么不直接做你想做的事呢。
<?php
$args_one = array(
\'cat\' => 7,
\'posts_per_page\' => 8,
);
$args_two = array(
\'cat\' => 10,
\'posts_per_page\' => 8,
);
// will run 2 sql queries.
$posts_one = get_posts( $args_one );
$posts_two = get_posts( $args_two );
$all_posts = array();
// lets merge them into 1 array.
while ( isset( $posts_one[0] ) || isset( $posts_two[0] ) ) {
if ( isset( $posts_one[0] ) ) {
$all_posts[] = array_shift( $posts_one );
}
if ( isset( $posts_two[0] ) ) {
$all_posts[] = array_shift( $posts_two );
}
}
/**
* Now we\'ve merged them gracefully into 1 array regarless of if these arrays are equal in size or not.
* so we can now render them in single loop.
*/
if ( count( $all_posts ) ) :
$num = 1;
global $post;
foreach ( $all_posts as $post ) :
setup_postdata($post);
if ( 0 === $num % 2 ) {
get_template_part( \'mobile-template/loop-even\' ); // i\'ve added suffix -even|-odd to make it possible to render them a bit differently.
} else {
get_template_part( \'mobile-template/loop-odd\' );
}
$num++;
endforeach;
wp_reset_postdata();
endif;