Make WordPress Core

Opened 15 years ago

Closed 15 years ago

#11461 closed defect (bug) (worksforme)

When creating a new WP_Query, running the_post() on the new object resets global $post

Reported by: bsdeluxe's profile bsdeluxe Owned by: ryan's profile ryan
Milestone: Priority: normal
Severity: normal Version:
Component: Query Keywords:
Focuses: Cc:

Description

This happens when running multiple loops in a page. If a new WP_Query object is created, $post should only be changed within the scope of that object, right?

To replicate:

// in a template called from a page

echo $post->ID; // the ID of the page
$new_obj = new WP_Query();
$new_obj->query("some valid querystring");
if ($new_obj->have_posts()) : while ($new_obj->have_posts()) : $new_obj->the_post();
 // .. do your loop stuff
endwhile; endif;
echo $post->ID; // not the same as the first one

Suggested patch attached.

Attachments (1)

the_post.2.patch (571 bytes) - added by bsdeluxe 15 years ago.
Patch to fix scope issue on the_post

Download all attachments as: .zip

Change History (6)

@bsdeluxe
15 years ago

Patch to fix scope issue on the_post

#1 @nacin
15 years ago

$post is a global central to a lot of WP functionality. What you're trying to do can be done via numerous multiple loop solutions. See http://codex.wordpress.org/The_Loop#Multiple_Loops.

#2 @scribu
15 years ago

  • Keywords close added; the_post wp_query scope post removed

What nacin said and also, with your patch, how would the global $post be populated in the main query?

Suggest closing as 'worksforme'.

#3 @filosofo
15 years ago

I like the general idea of trying to move the WP_Query away from being overly dependent on globals. Unfortunately there are huge backwards-compatibility issues. Practically everybody assumes $post will be defined in the scope of a template file. Lots of themes and theme examples use $post->ID to get the current post's ID within the Loop.

Someday maybe.

#4 follow-up: @dd32
15 years ago

call wp_reset_query() after your custom loop to reset it back to the main loop.

#5 in reply to: ↑ 4 @scribu
15 years ago

  • Keywords close removed
  • Milestone Unassigned deleted
  • Resolution set to worksforme
  • Status changed from new to closed

Replying to dd32:

call wp_reset_query() after your custom loop to reset it back to the main loop.

There you go.

Reopen when we drop PHP 4 for good.

Note: See TracTickets for help on using tickets.