Archived topic
Exclude Post Category From Block Element
5 replies · Started by Christian on April 1, 2022
Hi team!
I'm using a Block Element - Content Template in location Blog All Archives to display the latest blog posts in "Blog Archive Cards" but I'm having a bit of trouble figuring out how to exclude certain categories from showing.
Hi there,
are you wanting to remove ALL posts of specific category from displaying at all ?
Hey David!
Yes, I'd like to remove ALL posts of a specific category from displaying. For example, nothing in the category "Donuts" should be displayed. :)
OK - so the best way to go is to filter out the posts with a PHP snippet like so:
add_action('pre_get_posts', 'exclude_category_posts');
function exclude_category_posts( $query ) {
if($query->is_main_query() && !is_admin()) {
$query->set('cat', array( -22, -33 ));
}
}
In the array: array( -22, -33 ) you need to update those values to match the ID of the category term(s) you want to exluded. Note it has to be a -negative value. So if the post ID was 37 then you would use -37
Perfect, it works :)
Thanks David, you're a rockstar!
Glad to be of help!