query_posts() in function makes global $wp_query out of sync?

This has me stumped for a while already. Either I am missing something very obvious or something very not obvious. I am also not entirely sure if this has something to do with WP or purely PHP mechanics at work.

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

Result:

boolean true

boolean false

Why does test() evaluates that to true, but test2() evaluates that to false?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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: $foon";
failed_unset();
print "After failed_unset(): $foon";
successful_unset();
print "After successful_unset(): $foon";

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

Method 2

Have you tried using wp_reset_query(); after your custom query as described at http://codex.wordpress.org/Function_Reference/query_posts ?


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x