Support » Plugins » Hacks » category__not_in doesn't work

  • Resolved Satiro


    I tried to not repeat the categories in the loop by using the “category__not_in” query, but it doesn’t work. The code that I used is this:

    $my_query = new WP_Query(array('posts_per_page'=>6,'post__not_in'=>$do_not_duplicate,'category__not_in'=>$category__not_in));
    		if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post();
    		$do_not_duplicate[] = $post->ID;
    		$category = get_the_category();
    		$category__not_in[] = $category[0]->cat_ID;

    What can I do? Thanks in advance!

Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator bcworkz


    You can’t alter query results from inside the loop. And re-querying after each post would be highly inefficient. From inside the loop, you should use some sort of output control such as:

    if (!in_array($post->ID, $do_not_duplicate)) {
      $do_not_duplicate[] = $post->ID;

    You can nest the if(in_array())s as needed.

    Hi, sorry for the late reply.
    I tried with this:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
      $category = get_the_category();
      if (!in_array($category[0]->cat_ID, $do_not_duplicate)) :
        $do_not_duplicate[] = $category[0]->cat_ID;
        [SHOW POSTS]
    endwhile; else: ?>
    <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
    <?php endif; ?>

    Using this algorithm, doesn’t show the default number of posts on the page, cause one or more posts don’t comply with the if condition.
    What can I do?



    Forum Moderator

    it might help if you paste the full code of your template into a pastebin (see )
    to explain where the ‘do-not-duplicate’ arrays for this line come from:
    $my_query = new WP_Query(array('posts_per_page'=>6,'post__not_in'=>$do_not_duplicate,'category__not_in'=>$category__not_in));

    also, could you explain in more detail what “but it doesn’t work” really means?

    Moderator bcworkz


    alchymyth’s request would indeed be useful information, but I think we should backup and take a larger view. I think there’s a better approach to be taken for you to get the desired results. So what exactly are your desired results? First you wanted distinct posts, it appeared, now you appear to want distinct categories. If you can exactly describe what you want, perhaps we can figure out a good approach.

    Sorry for the mashup. I need to show the last 6 posts, one for each category (they’re 6 too). Then I’ve to avoid the repetition of categories and posts.

    I tried to do with this code:

    But it shows only 5 posts (sometimes less), because 1 or more posts don’t satisfy the if condition while the next post is retrieved.

    I solved it! Here the code:
    Thanks for your help!

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘category__not_in doesn't work’ is closed to new replies.