[wp-hackers] Resetting after multiple loops

Nigel Dunn nigel at redefine.co.uk
Mon Oct 27 09:25:32 GMT 2008


Hi Otto
]
On 25 Oct 2008, at 18:57, Otto wrote:

> wp_reset_query resets the global $wp_query, but with that code there's
> nothing needed to put something back to the original state because the
> $wp_query never got changed.
>
> What  "side_effects" are you seeing? The only side effect will be that
> the global $post and $id are used, because of the call to
> query->the_post(), but nothing else will change. And the $post and $id
> and such only affect those the_* functions, which are Loop-Only
> functions to begin with.
>
> In other words, a new WP_Query has no real side effects to speak of,
> and if you're seeing any, then you're doing something else wrong.

Yes you're right. After a bit more experimentation I can see that it's  
the query->the_post() that's causing me problems. Presumably for that  
something like

if (have_posts()) {
   the_post();
   rewind_posts();
}

would bring the $post and the $id globals back to their previous  
values (and any others).

Or I'd imagine the alternative would be to place that at the start of  
any widget to make sure that it was dealing with the post being  
viewed. I had been taking a different approach, in that anything that  
changed the globals should clean up after itself.

Has anybody covered this sort of thing in how to write widgets? Most  
of the documentation I've been referring to has been about the Loop,  
and that advice might not be as appropriate in this case. Other than  
that it's been using the code in wp-includes/widgets.php, which is  
where I'd started with this thread. I'd be happy to help expand the  
codex on this topic - but as you can see I have some unknown areas.

BTW - thanks for all who have been replying.

Cheers

Nigel

>
> On Sat, Oct 25, 2008 at 11:02 AM, Nigel Dunn <nigel at redefine.co.uk>  
> wrote:
>> Hi Otto
>>
>> Otto wrote:
>>>
>>> Harumph. Maybe I just like Object Oriented code more.
>>>
>>> $myquery = new WP_Query('whatever');
>>> while ($myquery->have_posts()) : $myquery->the_post();
>>> the_title();
>>> the_content();
>>> endwhile;
>>
>> I must admit that I'm with you on this, in fact I'd like to be able  
>> to do
>> $myquery->the_title(); etc.
>>
>> I had started with previous projects using get_posts but wasn't  
>> comfortable
>> with having to use global $post; to get it to work - and then  
>> seeing the
>> list of globals in function load_template() I was concerned about  
>> making
>> sure there weren't other side-effects.
>>
>> So I switched over to WP_Query after looking at the codex on loops  
>> as I had
>> hoped that wp_reset_query() would have put everything back to its  
>> original
>> state. But it doesn't seem to do that for me - have you had a  
>> similar issue
>> or is there something else I should be doing?
>>
>>

Nigel Dunn
Redefine

0845 838 2720
http://www.redefine.co.uk




More information about the wp-hackers mailing list