How to Exclude a Category From WordPress Loops
In this post, you will learn how to Exclude a Category From WordPress Loops. Use the below code snippets inside your theme’s functions.php file to exclude a category from WordPress loop.
/**
* Exclude a category from all WordPress loops
*/
add_action( 'pre_get_posts', function( $query ) { // anonymous callback
global $wp_query;
// Hard coded category ID, but can be dynamic: esc_attr(get_option('your-cat-id'));
$excluded_cat_id = 25;
// add category ID to existing, avoid overwritting it
$cat[] = $query->get( 'cat' );
$cat[] = "-" . $excluded_cat_id;
$query->set( 'cat', $cat );
}
});