3

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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