I'm trying to only display posts from a certain category in a widget. I've tried it in a few different ways but it is still showing posts from all categories. Here's my code at the moment:

$posts = get_posts(array ('category'=>6, 'numberposts'=>$number, 'order'=>'DESC', 'orderby'=>'date'));
        foreach ($posts as $post){



Did you try the example given in the codex?

global $post;
$args = array( 'numberposts' => $number, 'category' => 6, 'order' => 'ASC', 'orderby' => 'post_date'  );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :  setup_postdata($post); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>

This a modified version that should suit your needs. Are you also certain that this category exists?


<?php $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query('showposts=' . $numberposts . '&cat=6&orderby=date&order=ASC'); ?>
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
        <!-- your content -->
<?php endwhile; ?>
<?php $wp_query = null; $wp_query = $temp; ?>
|improve this answer|||||
  • The category definitely exists. I did try this code before and I double checked then with the code you provided but it doesn't work. Interestingly, it also didn't change the order despite it being changed from DESC to ASC. – Will Jun 15 '11 at 16:15
  • Try the code in my edit above, to see if it helps. – kevin Jun 15 '11 at 17:03

I guess you got 2 loops and maybe one before. Try to use wp_reset_query() before or rewind_posts().

|improve this answer|||||
  • No luck. Thanks though. – Will Jun 15 '11 at 16:38
  • Try to use 'category__in' as parameter. But dunno if all query_posts()/WP_Query arguments work there. – kaiser Jun 15 '11 at 16:39

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.