当前浏览:首页 / WordPress函数 / wp_reset_query()

wp_reset_query()

销毁前一个查询并建立新查询

querymore...

reset

  • wp_reset_postdata() 在执行一个独立的查询循环后,此函数将$post全局恢复为主查询中的当前post
  • wp_reset_query() 销毁前一个查询并建立新查询

描述

这应该在query_posts()之后和另一个query_posts()之前使用。将消除当前一个WP_Query对象在建立另一个对象之前未正确销毁时出现的模糊错误。


说明

query_posts()将更改您的主查询,不建议使用。仅在绝对必要时使用。二次循环首选是创建WP_Queryget_posts()的新实例。如果要修改主查询,请使用pre_get_posts动作钩子。



源码

查看源码 官方文档


更新日志

版本描述
2.3.0开始引入

使用示例

  • 示例1

    在自定义循环后使用

    下面的示例显示了如何在自定义循环后使用wp_reset_query()。注意,示例中的循环可能是在主循环之外使用的。

    <?php
    
    $args = array ( 'post_parent' => 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()将更改您的主查询,不建议使用。仅在绝对必要的情况下使用。对于二次循环,首选创建WP_Query或get_posts()的新实例。如果要修改主查询,请使用pre_get_posts动作钩子。请确保将pre_get_posts放在functions.php文件中。

    <?php
    query_posts( 'post_parent=5' );
    if ( have_posts() ) :
    	while ( have_posts() ) : the_post();
    		?><a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php
    	endwhile;
    endif;
    wp_reset_query();
    ?>