This is what you want to achieve as I understand:
If a post is assigned to a child category, then remove it and show only its parent on the categories list of that post.
You can use the following code to achieve that for any child category:
add_filter('get_the_terms', function($terms, $postId, $taxonomy) {
// Return early if not a category, there is an error, or we are on the dashboard.
if('category' !== $taxonomy || is_wp_error($terms) || is_admin()) {
return $terms;
}
// Create an array that will hold only parent categories
$parents = [];
// Loop on all the terms, keep the parents or get the parent of any child
foreach ($terms as $term) {
// This is a parent, add it and continue
if(! $term->parent) {
$parents[$term->term_id] = $term;
continue;
}
// This is a child get its parent and add it
$parent = get_term($term->parent, $taxonomy);
if(is_a($parent, 'WP_Term')) {
$parents[$parent->term_id] = $parent;
}
}
// Finally, reset the array keys and return it
return array_values($parents);
}, 10, 3);
But, if you want to do this for only a selected list of child categories, use this code:
add_filter('get_the_terms', function($terms, $postId, $taxonomy) {
// Return early if not a category, there is an error, or we are on the dashboard.
if('category' !== $taxonomy || is_wp_error($terms) || is_admin()) {
return $terms;
}
// Categories to exclude
$excludedIds = [31, 32, 33, 34, 35, 36, 37, 38, 96];
// Create an array that will hold only not excluded categories
$categoriesToKeep = [];
// Loop on all the terms, and replace the excluded categories with their parents
foreach ($terms as $term) {
// This is not in the excluded list, add it and continue
if(! in_array($term->term_id, $excludedIds)) {
$categoriesToKeep[$term->term_id] = $term;
continue;
}
// This an excluded category, replace it with its parent
$parent = get_term($term->parent, $taxonomy);
if(is_a($parent, 'WP_Term')) {
$categoriesToKeep[$parent->term_id] = $parent;
}
}
// Finally, reset the array keys and return it
return array_values($categoriesToKeep);
}, 10, 3);