0

I come with a basic question but I can not solve, I think that will be easy for you. I would like, if I have 2 or more post on loop, show the entire loop. I tried the following:

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$portfolio = new WP_Query(array('post_type' => 'project', 'posts_per_page' => 12, 'paged' => $paged));
$count = 0; ?>

<?php if ($portfolio < 2) : ?>

        [CONTENT LOOP]
    <?php if ($portfolio) :  while ($portfolio->have_posts()) : $portfolio->the_post();
        [/CONTENT LOOP]

        <?php endwhile; ?>
    <?php endif; ?>
<?php endif; ?>

However, that didnt work, the single post still appearing. Like I said, if i have one post in the loop, will show nothing of the loop. Sorry for the question, is that I'm not very familiar with wordpress yet. Thank you!

1 Answer 1

0

If you want to check the number of posts on each page, you can use the found_posts method of WP_Query :

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$portfolio = new WP_Query(array('post_type' => 'project', 'posts_per_page' => 12, 'paged' => $paged));
if ($portfolio && $portfolio->found_posts >= 2) :  
    while ($portfolio->have_posts()) : $portfolio->the_post();
        echo "<div>";
        the_title();
        echo "</div>";
    endwhile; 
endif;
wp_reset_postdata();
?>

and here we use $portfolio->found_posts >= 2 to check if we got 2 or more posts on the page. Finally wp_reset_postdata() is added to restore the global $post to the current post in the main query.

2
  • Thanks a lot! Im not using wp_reset_postdata(), this is a problem? Mar 8, 2013 at 21:44
  • It is good to have it just in case you have another code below that uses the global $post variable. It's like cleaning up after the custom query ;-)
    – birgire
    Mar 8, 2013 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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