-1

I'm very confused regarding the have_posts(). It returns an empty result even though I have one post that match the query.

The below code is used in a widget which should display exactly one post, if it exists. I use wordpress 3.3...

$singleargs = array('p' => 2040, 'post_type' => 'event', 'post_status' => array('any'), 'posts_per_page' => 1);
$singlequery = new WP_Query( $singleargs );
//print_r($singlequery);
echo "I'm here 1!!<br>";
while ( $singlequery->have_posts() ) :
echo "I'm here 2!!<br>";
$singlequery->the_post();
// output post data...
endwhile;

The above code outputs only "I'm here 1!!", nothing else. But if I remove the while ( $singlequery->have_posts() ) : and endwhile; then I get "I'm here 1!!", "I'm here 2!!" and the correct output of the post that was found. So why do $singlequery->have_posts() not return true!!???

  • what's the 'p'=>2040 doing in the args array? – ptriek Dec 14 '11 at 18:30
  • +1 with @ptriek... Why the id? It can change if you move between WP installations. And if you still want to use the id, why not use get_posts instead? – Rutwick Gangurde Dec 14 '11 at 18:46
  • The query only has one result because you're specifying the ID inside the arguments, it can't possibly return more than 1 result because IDs are unique, ie. the p => x part. – Mark Duncan Dec 14 '11 at 21:02
1

Can you try changing your query to this?

$singleargs = array('post_type' => 'event');

It looks like that's what you're going for. The rest of the parameters limits your result to zero or 1.

Also, make sure that the post type name is spelled correctly in your query.

0

Doesn't

'post_status' => array('any')

Break the query?

I always use

'post_status' => null

In my code.

By the way, if you know the post id, why just not skip all of the paramaters and just use the 'p'? All of the other parameters are kind of useless then :-)

Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.