The problem here is you're not using the proper hook because the_category
is actually for modifying the HTML of the category list, and the 1st parameter for the hook is actually a string and not an array.
So the hook that you should have used is the_category_list
where the 1st parameter is an array of terms/categories, but note that each item is an object (a WP_Term
instance) and not a category ID.
And with your current code, you just need to make 2 changes:
Change the add_filter()
to using the_category_list
instead:
add_filter('the_category_list','my_category_filter');
In your foreach
, change the if
to using $cat->term_id
instead:
if (!in_array($cat->term_id,$exclude))
So now your code should work correctly, but it also would work on any "current post", e.g. the one in the current loop, so you might need to add a condition to your function so that it only applies to specific posts.
Or you could actually manually generate the categories list/HTML, e.g. using get_the_category()
:
// ID's of the categories you want to be excluded.
$exclude = array( 4 );
// The categories list.
$cat_list = array();
foreach ( get_the_category() as $cat ) {
if ( ! in_array( $cat->term_id, $exclude ) ) {
$cat_list[] = '<a href="' . esc_url( get_category_link( $cat->term_id ) ) .
'">' . $cat->name . '</a>';
}
}
// Display a simple comma-separated list of links.
echo implode( ', ', $cat_list );
Then in your template, use the above code instead of the the_category()
. That way, you can avoid messing with the categories list for other "current post".
$Catds
should be$Catsa
..