WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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(); 

share|improve this question

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' 
share|improve this answer
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 Dec 16 '12 at 14:40
Excluding those categories is easy. Updated the code. – s_ha_dum Dec 16 '12 at 15:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.