Exclude post with category A, but not with A and B
-
I am looking to exclude posts with a particular category, but not when they also have a second category that is not excluded. So if I have categories A, B, C and D, I want to include all posts except those categorized ONLY A.
I know that I can exclude a category by placing the following in functions.php
function exclude_category( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', '-2' ); } } add_action( 'pre_get_posts', 'exclude_category' );
but then any post with category ID 5 is excluded regardless of what other categories the post may have.
I could also expressly include all categories except the excluded one
function include_categories( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', '3,4,5' ); } } add_action( 'pre_get_posts', 'include_categories' );
but I would rather not need to rewrite functions.php every time the blog adds a new category.
Is there a way (or a plug-in) that can operate like the second function without needing to be recoded when new categories are added?
- The topic ‘Exclude post with category A, but not with A and B’ is closed to new replies.