函数中的Query_Posts()是否使全局$wp_Query不同步?

时间:2011-04-02 作者:Rarst

这已经让我困惑了一段时间。要么我错过了一些非常明显的东西,要么我错过了一些非常不明显的东西。我也不完全确定这是否与工作中的WP或纯粹的PHP机制有关。

function test() {

    global $wp_query;

    var_dump($wp_query == $GLOBALS[\'wp_query\']);
}

function test2() {

    global $wp_query;

    query_posts(array(\'posts_per_page\' => 1));
    var_dump($wp_query == $GLOBALS[\'wp_query\']);
}

test();
test2();
结果:

布尔值true

布尔假

为什么test() 将其评估为true, 但是test2() 将其评估为false?

2 个回复
最合适的回答,由SO网友:fuxia 整理而成

Update with a better example

header( \'Content-Type: text/plain;charset=utf-8\' );
error_reporting( E_ALL | E_STRICT );

function failed_unset()
{   // Copy the variable to the local namespace.
    global $foo;

    // Change the value.
    $foo = 2;

    // Remove the variable.
    unset ( $foo );
}
function successful_unset()
{
    // Remove the global variable
    unset ( $GLOBALS[\'foo\'] );
}

$foo = 1;
print "Original: $foo\\n";
failed_unset();
print "After failed_unset(): $foo\\n";
successful_unset();
print "After successful_unset(): $foo\\n";

Result

Original: 1
After failed_unset(): 2

Notice: Undefined variable: foo in /srv/www/htdocs/global-unset.php on line 21

Call Stack:
    0.0004     318712   1. {main}() /srv/www/htdocs/global-unset.php:0

After successful_unset():

unset() doesn’t know anything about the global scope in the first function; the variable was just copied to the local namespace.


Old answer

From wp-includes/query.php:

function &query_posts($query) {
    unset($GLOBALS[\'wp_query\']);
    $GLOBALS[\'wp_query\'] =& new WP_Query();
    return $GLOBALS[\'wp_query\']->query($query);
}

Do you see it?

BTW: Someone has made a nice flowchart about this very topic. ;)

Update

query_posts() changes $GLOBALS while all references to the variable $wp_query that you made available per global are not affected by unset. That’s one reason to prefer $GLOBALS (besides readability).

SO网友:cwd

你试过使用wp_reset_query(); 如中所述的自定义查询之后http://codex.wordpress.org/Function_Reference/query_posts ?

结束

相关推荐