You might try this kind of pre_get_posts
hook approach (untested):
add_action( 'pre_get_posts', function( $q )
{
$exclude_cats = [ 12, 34 ]; // <-- Edit thisthese category ids!
if( ! is_admin()
&& $q->is_main_query()
&& ! is_singular()
&& ! is_category( $exclude_cats )
)
{
$exclude_post_ids = get_posts(
[
'fields' => 'ids',
'posts_per_page' => 5,
'category__in' => $exclude_cats,
]
);
$q->set( 'post__not_in', (array) $exclude_post_ids );
}
} );
where you might have to adjust this further to your needs.
You also might want to use category slugs instead, but then you would have to setup a proper tax_query
, since category__in
only supports an array of category ids.