具有嵌套输出的多个WordPress查询(奇偶)

时间:2020-03-13 作者:shahriyar.m

我需要显示两个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标准的方法。

1 个回复
最合适的回答,由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;

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post