WordPress - 恢复原始WP_Query

时间:2012-06-27 09:57:04

标签: php wordpress loops

我有一个名为“Portfolio”的帖子类型和单一的portfolio.php文件来处理它(它是WordPress)。当我在那里使用类似的东西时,它会像预期的那样工作:

$post_id = $post->ID; //returns ID of current portfolio post. Good!

但是当我在中间发布这样的简短查询时:

$post_id = $post->ID; //returns ID of current portfolio post. Good!
wp_reset_query();
query_posts('posts_per_page=4');
    if ( have_posts() ) : while ( have_posts() ) : the_post();
            the_id(); //returns ID of standard blog post
        endwhile;
    endif; 
wp_reset_query();
$post_id = $post->ID; //returns ID of last BLOG post. Wrong!

我只关注上面例子中的$post_id变量。我希望它始终返回当前PORTFOLIO帖子的正确ID,而不依赖于其他查询。我如何实现这一目标?

2 个答案:

答案 0 :(得分:3)

我相信wp_reset_postdata()会为您提供所需的结果。

$the_query = new WP_Query( 'posts_per_page=4' );

if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        // output
    endwhile;
endif;

wp_reset_postdata();

我应该注意到我有另一种方法documented in another question asking about what is the difference and when each should be used

答案 1 :(得分:0)

wp_reset_query函数也会重置全局$post变量,但仅基于全局$wp_query变量。这仍然是修改,可能是由于Wordpress中的一个小缺陷。在你的情况下,我会说一个简单的WP_Query::rewind_posts()应该这样做:

wp_reset_query();
$wp_query->rewind_posts();
$post_id = $post->ID;

此外,您应该考虑创建第二个循环,而不是覆盖第一个循环。

参见:

相关问题