WordPress.org

Make WordPress Core

Opened 4 years ago

Closed 4 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 Owned by: 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 4 years ago.
Patch to fix scope issue on the_post

Download all attachments as: .zip

Change History (6)

bsdeluxe4 years ago

Patch to fix scope issue on the_post

comment:1 nacin4 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.

comment:2 scribu4 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'.

comment:3 filosofo4 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.

comment:4 follow-up: dd324 years ago

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

comment:5 in reply to: ↑ 4 scribu4 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.