Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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!!???

share|improve this question
    
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
add comment

2 Answers

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.

share|improve this answer
add comment

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!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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