Support » Fixing WordPress » Post in multiple categories- get posts excluding one cat

  • Resolved chachalady


    I have posts that can be both in category ‘5’ and ‘152’ at the same time.
    In right sidebar I have to retrieve posts from category ‘5’ but excluding category ‘152’ from that post listing.
    – now you wonder why am I here then, right? !!! 🙂
    1) Here is the code of a working solution:

    $lastposts = get_posts('numberposts=7&cat=5&category__not_in=152');
            foreach($lastposts as $post) :
    <a href="<?php the_permalink(); ?>" target="_blank">
    <?php the_title(); ?></a>
    <?php endforeach; ?>

    2) Here is the code that was NOT working, it was displaying posts also from cat=’152′ despite of the exclude ‘cat__not_in’ :

    	'cat' => 5,
    	'cat__not_in' => array(152),
    	'post_type' => 'post',
            'post_status' => 'publish',
    	'order' => 'DESC',
    	'posts_per_page' => 5
         query_posts( $args ); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <a href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a>
    <?php endwhile; else: ?>
    <li><?php _e('No other news.'); ?></li>
    <?php endif; ?>

    Please, for a benefit of a future projects 🙂 , can a good souls that exists on this forum explain to me WHY OH WHY the method 2) with $args in array won’t work in my case?

    It was just a lucky coincidence that I tried the working solution.
    But some bug in me won’t let me sleep well till I find a reason why.
    I need my beauty sleep :-/
    Your explanation will help me and many other nonsleeping wordpressers, I am sure … thank you, thank you, thank you 😉

Viewing 3 replies - 1 through 3 (of 3 total)
  • If you posted the actual code for the $args array, then the problem appears to be that you used ‘cat__not_in’ instead of ‘category__not_in’.

    OMG, yes, that’s the actual code … with ‘category__not_in’ both examples are working ok.

    Thank you very much – how silly of me – I didn’t even realise the diffeence…. !

    Browsing through forums I am sure I saw ‘cat__not_in’ … so I thought I can write it that way …

    All in all – now everybody can see both examples of excluding posts from specific category.


    We can now mark this as resolved 🙂

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Post in multiple categories- get posts excluding one cat’ is closed to new replies.