Support » Everything else WordPress » How can I exclude category # in a loop

  • In my sidebar template, I have a loop that finds out what categories a post belongs to and then lists recent posts for each category. I need to be able to have it skip one of more specific category numbers.

    For example, if a post is in category 1, 2, and 3, I only want it to display the related posts for category 2, but not display the related posts for categories 1 and 3.

    Here is the code I have. I imagine it is simple, I just can’t figure out the syntax to get it to skip past the unwanted categories.

    // this is where 10 headlines from the current category get printed
    if ( is_single() ) :
    global $post;
    $categories = get_the_category();
    foreach ($categories as $category) :
    <li><h2>More from this category</h2>
    <ul class="bullets">
    $posts = get_posts('numberposts=10&category='. $category->term_id);
    foreach($posts as $post) :
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>
    <li><strong><a href="<?php echo get_category_link($category->term_id);?>" title="View all posts filed under <?php echo $category->name; ?>">Archive for '<?php echo $category->name; ?>' &raquo;</a></strong></li>
    <?php endforeach; endif ; ?>
  • The topic ‘How can I exclude category # in a loop’ is closed to new replies.