[wp-hackers] Testing for existence of WP_Query results

Ade Walker photofantaisie at gmail.com
Thu Aug 13 19:17:40 UTC 2009


@ Chis,

Thanks! That's what I thought re objects, but I hadn't thought of the
obvious if($recent->have_posts().

@ Ashok,

Thanks for the reply,

Ade.

2009/8/13 Ashok Padda <ashok.padda at gmail.com>

> Hi Ade,
>
> Please try using if($recent->have_posts()) instead of if($recent)
>
> Following code worked for me
> ------------------------------x------------------------------
> $recent = new WP_Query('category_name=special_category');
>   if ($recent->have_posts()) :
>    while($recent->have_posts()) : $recent->the_post();
>       the_content();
>    endwhile;
>  else :
>    echo 'No posts are posted in the category';
>  endif;
> ------------------------------x------------------------------
>
> +Ashok
>
> On Fri, Aug 14, 2009 at 12:20 AM, Chris Scott <cjscott69 at gmail.com> wrote:
>
> > On Thu, Aug 13, 2009 at 2:39 PM, Ade Walker<photofantaisie at gmail.com>
> > wrote:
> > > Hi all,
> > >
> > > This probably exposes my lack of PHP knowledge, and understanding of
> the
> > > WP_Query object, but I came across the following situation with a
> plugin
> > of
> > > mine recently.
> > >
> > > In order to test that a WP_Query had actually found posts, I used this
> > > conditional check
> > >
> > > $recent = new WP_Query(args);
> > > if($recent) :
> > > while($recent->have_posts()) : $recent->the_post();
> > > // rest of loop etc
> > >
> > > else :
> > > // do something else
> > >
> > > But I found that if($recent) nevers returns false, even if no posts are
> > > found.
> > >
> > > Is there a different way to test (before the while loop runs) that any
> > posts
> > > were found by the query?
> >
> > Try:
> >
> > $recent = new WP_Query(args);
> > if($recent->have_posts()) :
> > while($recent->have_posts()) : $recent->the_post();
> > ...
> >
> > if($recent) will always be true in your case because it is an object.
> >
> > --
> > Chris Scott
> > http://iamzed.com/
> > http://hailtheale.com/
> >
> >
> >
> > >
> > > I'm probably overlooking something blindingly obvious - but I just
> can't
> > see
> > > it... :-/
> > >
> > > Thanks!
> > >
> > > Ade.
> > > _______________________________________________
> > > wp-hackers mailing list
> > > wp-hackers at lists.automattic.com
> > > http://lists.automattic.com/mailman/listinfo/wp-hackers
> > >
> > _______________________________________________
> > wp-hackers mailing list
> > wp-hackers at lists.automattic.com
> > http://lists.automattic.com/mailman/listinfo/wp-hackers
> >
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>


More information about the wp-hackers mailing list