[wp-hackers] Knowing when you're in The Loop, and when you're not

Mark Jaquith mark.wordpress at txfx.net
Sat Jul 16 04:14:43 GMT 2005


Mark Jaquith wrote:

> Then, this function (within the class) could test for "in the loop"-ness
>
>> function in_the_loop() {
>>     if ($this->post_count && $this->current_post + 2 == 
>> $this->post_count) {
>>     return false; // loop has been run already
>>     } elseif (!$this->current_post) {
>>     return false; // loop hasn't started
>>     } else {
>>     return true; // in the loop
>>     }
>> }
>
Actually, it because $this->current_post is initialized at -1, you'd 
have to do something else... because $this->current_post can equal 0 
when you're in the loop.

Here's one way:

> function in_the_loop() {
>     if ($this->post_count && $this->current_post + 2 == 
> $this->post_count) {
>     return false; // loop has been run already
>     } elseif ($this->current_post < 0) {
>     return false; // loop hasn't started
>     } else {
>     return true; // in the loop
>     }
> }


Another way would be to have $wp_query->have_posts() set 
$this->current_post to -2 when the end of the last loop iteration is 
reached.  -1 could stand for "hasn't started yet" and -2 could stand for 
"has already run."

Or, you could just have a $this->in_loop; variable that is set as true 
with the first the_post() call and set false on the last have_posts() call.

-- 
Mark Jaquith
http://txfx.net/
MCincubus @ #wordpress



More information about the wp-hackers mailing list