It's similar to Exclude sub category posts from category display but I want it only for a specific post. This post appears in multiple categories and subcategories, but I only want it to be shown in subcategories, not categories.
1 Answer
Ended up doing this (if the relevant post's ID is, for example, 5):
function filter_posts($query) {
if ( $query->is_category() && $query->is_main_query()) {
$this_category = get_queried_object();
if (0 == $this_category->parent) // Category has no parent
$query->set('post__not_in', array('5'));
}
}
add_action('pre_get_posts', 'filter_posts');