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 trying to list all posts from a certain category, in a list, on the category page that already lists the posts out in blog form. I'm trying to do it in the header area so that you can get an overall look at the posts on the page. I found this:

<ul>
<?php
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;
$myposts = get_posts(array('numberposts' => 5, 'category__in' => array($category), 'post__not_in' => array($post->ID),'post_status'=>'publish'));
foreach($myposts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a>
</li>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
</ul>

But it always seems to cut one of the posts out of the list. Is there an easier way to do this, without a plugin?

Thanks

share|improve this question
add comment

1 Answer

up vote -1 down vote accepted

Good news! I think you're making things harder for yourself than they need to be. If I understand your question, you're looking for rewind_posts(). The always useful Digging Into WordPress has a nice summary of it.

Because both tasks involve looping through the same query, you don't need get_posts() at all.

Instead, you'll want to use the aforementioned rewind_posts() something like this:

<?php if( have_posts() ) : ?>
<!-- Your list of posts -->
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

<?php rewind_posts(); // second <del>verse</del> query, same as the first ?>

<?php while( have_posts() ) : the_post(); ?>

<!-- your "blog-style" stuff -->

<?php endwhile; endif; ?>
share|improve this answer
    
Spot on, thanks, I'll look into how rewind_posts works a little more as well. –  Phill May 11 '12 at 10:47
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.