0

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

1 Answer 1

1

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; ?>
1
  • Spot on, thanks, I'll look into how rewind_posts works a little more as well.
    – Phill
    Commented May 11, 2012 at 10:47

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.