get_the_category()
has a filter, get_the_categories
, that will filter the categories. You can do something like this:
add_filter( 'get_the_categories', 'wpse426499_filter_categories' );
/**
* Filters the categories.
*
* @param WP_Term[] $categories An array of WP_Term (ie, category) objects.
* @return WP_Term[] The filtered array of WP_Term objects.
*/
function wpse426499_filter_categories( $categories ) {
$undesired_id = 2; // Set this to the ID of the category you want to exclude.
// New array for the category objects.
$filtered = array();
foreach ( $categories as $cat_obj ) {
if ( $cat_obj->term_id != $undesired_id ) {
// If this isn't the unwanted category, add it to the array.
$filtered[] = $cat_obj;
}
}
// Return the array.
return $filtered;
}
You can put this code in the functions.php
file of your active theme, or — if you’re thinking of changing themes at some point — you can make it into a plugin.