【问题标题】:WordPress - restore original WP_QueryWordPress - 恢复原始 WP_Query
【发布时间】:2012-06-27 09:57:03
【问题描述】:

我有一个名为“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,而不依赖于其他查询。我该如何实现?

【问题讨论】:

  • 我找到了一种使用 $temp = $post; 的方法和 $post = $temp;查询后,但我认为这不是官方推荐的方式。

标签: php wordpress loops


【解决方案1】:

我相信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

【讨论】:

    【解决方案2】:

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

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

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

    参见:

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2019-12-23
      • 2015-12-09
      • 2019-05-22
      相关资源
      最近更新 更多