Get only one of the current categories

On post pages Im using the below code to display links to other posts from the current category.

My problem is when the current post is in more than 1 category it will display posts from the first category only.

Read More

I want to control which current categories it shows posts from by excluding certain categories Ids (e.g. 29, 35)

Any ideas would be greatly appreciated.

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

?>
</ul>
<?php

Related posts

Leave a Reply

1 comment

  1. get_the_category should be returning all of the categories for your post, but you are only picking one of them, the first one, when you do this– $category = $category[0]->cat_ID;. Instead of that line try:

    $allcats = array();
    foreach ($category as $cat) {
      if (29 != $cat->cat_ID && 35 != $cat->cat_ID) {
        $allcats[] = $cat->cat_ID;
      }
    }
    $myposts = get_posts(
      array(
        'numberposts' => 5, 
        'offset' => 0, 
        'category__in' => $allcats,  
        'post_status'=>'publish', 'order'=>'ASC' 
    ));