wp_reset_query()恢复$post全局变量,销毁之前的查询

目录

描述

wp_reset_query() restores the $wp_query and global post data to the original main query. This function should be called after query_posts(), if you must use that function. As noted in the examples below, it's heavily encouraged to use the pre_get_posts filter to alter query parameters before the query is made.

Calling wp_reset_query is not necessary after using WP_Query or get_posts as these don't modify the main query object. Instead use wp_reset_postdata

wp_reset_query() 描述

用法

<?php wp_reset_query(); ?>

wp_reset_query() 用法

参数

This function does not accept any parameters.

wp_reset_query() 参数

返回值

This function does not return any values.

wp_reset_query() 返回值

示例

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.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?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() 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.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?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();
?>

wp_reset_query() 示例

历史

  • 添加于 版本: 2.3.0

wp_reset_query() 历史

源文件

wp_reset_query() 函数的代码位于 wp-includes/query.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Destroy the previous query and set up a new query.
 *
 * This should be used after {@link query_posts()} and before another {@link
 * query_posts()}. This will remove obscure bugs that occur when the previous
 * wp_query object is not destroyed properly before another is set up.
 *
 * @since 2.3.0
 *
 * @global WP_Query $wp_query
 * @global WP_Query $wp_the_query
 */
function wp_reset_query() {
	$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
	wp_reset_postdata();
}

wp_reset_query() 源文件

相关