函数文档

wp_reset_query()

💡 云策文档标注

概述

wp_reset_query() 函数用于销毁之前的查询并设置新查询,主要解决在使用 query_posts() 后可能出现的错误。它通过恢复全局查询对象来确保查询状态正确重置。

关键要点

  • 应在 query_posts() 之后、另一个 query_posts() 之前使用,以避免因 WP_Query 对象未正确销毁导致的错误。
  • query_posts() 会改变主查询,不推荐使用;建议使用 WP_Query 或 get_posts() 创建辅助循环。
  • 修改主查询应使用 pre_get_posts action,并将过滤代码放在 functions.php 文件中。
  • 与 wp_reset_postdata() 相关,后者用于在单独查询循环后恢复 $post 全局变量到主查询的当前文章。

代码示例

$args = array(
    'posts_per_page' => 5
);
query_posts( $args );

if ( have_posts() ):
    while ( have_posts() ) :
        the_post();
        // 处理文章内容
        the_title();
        the_permalink(); // 等
    endwhile;
else:
    // 无文章时的内容或模板
endif;

wp_reset_query();

注意事项

wp_reset_query() 自 WordPress 2.3.0 版本引入,使用时需注意 query_posts() 的局限性,优先考虑更安全的替代方案。


📄 原文内容

Destroys the previous query and sets up a new query.

Description

This should be used after query_posts() and before another query_posts() .
This will remove obscure bugs that occur when the previous WP_Query object is not destroyed properly before another is set up.

More Information

query_posts() will change your main query and is not recommended. Only use if absolutely necessary. Creating a new instance of WP_Query or get_posts() is preferred for secondary loops. If you would like to modify the main query, use the pre_get_posts action.

Source

function wp_reset_query() {
	$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
	wp_reset_postdata();
}

Changelog

Version Description
2.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Using after a Custom Loop

    The following example shows how to use wp_reset_query() after a custom loop. Note that the loop in the example is probably being used in addition to the main loop.

     5 );
    query_posts( $args );
    
    if ( have_posts() ):
        while ( have_posts() ) :
            the_post();
    
            // Do stuff with the post content.
            the_title();
            the_permalink(); // Etc.
    
        endwhile;
    else:
        // Insert any content or load a template for no posts found.
    endif;
    
    wp_reset_query();
    
    ?>

    query_posts() will change your main query and is not recommended. Only use if absolutely necessary (see query_posts: Caveats). Creating a new instance of WP_Query or get_posts() is preferred for secondary loops. If you would like to modify the main query, use the pre_get_posts action. Be sure to put your pre_get_posts filtering in your functions.php file.

    <a href="<?php the_permalink() ?>"></a><br />