1

I need to filter posts that belong to a category only if that is the only category. For example if my post A belongs to cat1 and I don't want to display posts that belong to cat1, post A won't be displayed. But if post A belongs to cat1 and cat2 it will be displayed as I don't want to filter cat2.

I tried to do something like this:

<?php while (have_posts()) : the_post(); ?>

$category_to_exclude = 11;
while ( have_posts() ) : the_post();
$categories = get_the_category();
if( in_array($category_to_exclude, $categories) && count($categories) > 1 ) {
    the_title();
    the_content();
}
endwhile;

but of course it doesn't work properly as "cut off" posts only. It should filtered directly from the query used to get the posts but I don't know how to write this query. Any idea?

2
  • Where do you want to place it? category.php?
    – Max Yudin
    Feb 3, 2013 at 11:12
  • it is in the list of posts in home page - changing my theme's loop.php
    – Randomize
    Feb 3, 2013 at 11:15

1 Answer 1

2

You will need more than one query because before querying posts you have to know what posts to exclude.

I personally don't see anything bad in 'cutoff'. This code should work properly:

Update: It breaks pagination (see comments).

<?php
$category_to_filter = 11;
while ( have_posts() ) : the_post();
    $categories = get_the_category();
    if( in_array($category_to_filter, $categories) && count($categories) > 1 ) {
        the_title();
        the_content();
    }
endwhile;

Update: Following code will not break pagination:

<?php
$category_to_filter = 11;
$posts_in = array();
while ( have_posts() ) : the_post();
    $categories = get_the_category();
    if( in_array($category_to_filter, $categories) && count($categories) > 1 ) {
        $posts_in[] = $post->ID;
    }
endwhile;

$my_query = new WP_Query( array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'post__in' => $posts_in
    )
);

while ( $my_query->have_posts() ) : $my_query->the_post();
    // your template stuff here
endwhile;
wp_reset_query();
2
  • thank for the code cleaning. The problem with it is based on the reported list of elements in pagination. For example if you have 10 posts per page, and in one page you have 3 posts to hide, it will show only 7 posts and not 7 posts + 3 next posts candidate to inclusion.
    – Randomize
    Feb 3, 2013 at 11:26
  • Oh, I see. I'll add the new code to my answer now.
    – Max Yudin
    Feb 3, 2013 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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