Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am looking to exclude a category in Wordpress. I am referring to the Wordpress Codex page on wp_query but I am having the following problem:

  1. I want to exclude posts from category 1,
  2. but if a post is in category 1 and category 2 (or any other category other than 1), then I still want it to show.

So, I only want posts to be excluded if they're exclusively in category 1.

share|improve this question
    
Please follow up on the questions you asked, it's an important part of the process on WPSE - see What should I do when someone answers my question? and Why is voting important? for a deeper insight. Thank you! –  ialocin Nov 7 '13 at 12:55

1 Answer 1

This can be done by getting an array of category ids you want to show. We can use get_terms() for this:

$taxonomy = array(
    'category'
);
$args = array(
    'exclude' => array('111'),//id of the category term you want to exclude  
    'fields' => 'ids'
);
$ct_ids = get_terms( $taxonomy, $args );

Now you can use this to create your secondary query with WP_Query by using the Category Parameter category__in like this:

$args = array(
    'category__in' => $ct_ids
);
$scnd_query = new WP_Query( $args );

If you for example want to do this just for your home page, than there is no need for a custom secondary query, you can achieve it by hooking into the pre_get_posts action like this:

function show_all_but_category_xyz( $query ) {
    if ( !is_admin() && $query->is_home() && $query->is_main_query() ) {
        $query->set( 'category__in', $ct_ids );
    }
}
add_action( 'pre_get_posts', 'show_all_but_category_xyz' );
share|improve this answer

Your Answer

 
discard

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.