将POSTDATA重置为嵌套查询中的自定义查询

时间:2017-12-20 作者:galingong

我有一个主查询,在其中我设置了一个新的自定义查询来检索帖子(想想“相关帖子”之类的)。在这些帖子中,我设置了另一个自定义查询,从单个帖子加载数据,然后我应该找到一种方法将postdata重置为第一个自定义查询。我该怎么做?我尝试了wp\\u reset\\u postdata(),但这会重置为主查询。

简化的代码如下所示:

while ( have_posts() ) : the_post();

    //Set up custom query
    $args = array(
        //Query args
    );
    $custom_query = new WP_Query( $args );

    //Custom query loop:
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        //Display some data,

        //then set up a custom query again
        $args = array(
            //Different query args
        );
        $custom_nested_query = new WP_Query( $args );

        //Nested custom query loop
        while ( $custom_nested_query->have_posts() ) : $custom_nested_query->the_post();
            //Do stuff, then reset to $custom_query since
            //I still need the post before $custom_query proceeds with the loop and loads the next one
        endwhile;

        //Display some more data from post queried by $custom_query before $nested_query was created
    endwhile;
endwhile;

1 个回复
SO网友:Shibi

您可以保存$post 在一些温度变量中,只需设置$post 返回temp变量

global $post;
while ( have_posts() ) : the_post();

    //Set up custom query
    $args = array(
        //Query args
    );
    $custom_query = new WP_Query( $args );

    //Custom query loop:
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        // Save global post into temp variable
        $temp_post = $post;

        //Display some data,

        //then set up a custom query again
        $args = array(
            //Different query args
        );
        $custom_nested_query = new WP_Query( $args );

        //Nested custom query loop
        while ( $custom_nested_query->have_posts() ) : $custom_nested_query->the_post();
            //Do stuff, then reset to $custom_query since
            //I still need the post before $custom_query proceeds with the loop and loads the next one
        endwhile;

        // Set the global $post back to the first custom query
        $post = $temp_post;
        //Display some more data from post queried by $custom_query before $nested_query was created

    endwhile;
    wp_reset_postdata();
endwhile;
或者只是使用foreach($custom_nested_query->posts as $mypost).

结束

相关推荐

Twenty Seventeen Pages Loop

有人能向我解释一下,在静态主页的2017主题中,它在哪里被引导去循环页面而不是帖子?我不明白它是在哪里这样做的,从一个新的WordPress安装。在里面front-page.php 我有这个:<?php // Get each of our panels and show the post data. if ( 0 !== twentyseventeen_panel_count() || is_customize_preview() ) : // If