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.

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.

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) :
<a href="<?php the_permalink(); ?>">
<?php echo get_post_meta($post->ID, "rw_post_type", true); ?></a>
<?php endforeach; ?>
<?php wp_reset_query(); 


1 Answer 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(
    'numberposts' => 5, 
    'offset' => 0, 
    'category__in' => $allcats,  
    'post_status'=>'publish', 'order'=>'ASC' 
  • Thanks for the reply but maybe my question was not clearer enough. I understand I am only picking one category, and this is what I am aiming to do. Most of the time the category I want is the first category but occasionally it will not be because categories 29 and 35 will be first. I want to update the code so that it ignores these two categories. Does this make sense?
    – Ben
    Commented Dec 16, 2012 at 14:40
  • Excluding those categories is easy. Updated the code.
    – s_ha_dum
    Commented Dec 16, 2012 at 15:12

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.