Excluding posts from a category but only if they’re not in multiple categories

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

Leave a Comment