返回介绍

wp_reset_query()

发布于 2017-09-11 12:45:59 字数 2571 浏览 1017 评论 0 收藏 0

wp_reset_query()

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.


源代码

File: wp-includes/query.php

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

更新日志

Versiondescription
2.3.0Introduced.

相关函数

Uses

  • wp-includes/query.php: wp_reset_postdata()

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 0You must log in to vote on the helpfulness of this note Contributed by Codex

    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.

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文