There is no filter for the_category
. All that the_category
does is to echo
get_the_category_list
. Have a look at the function in wp-includes/category-template.php lines 273 – 275
273 function the_category( $separator="", $parents="", $post_id = false ) {
274 echo get_the_category_list( $separator, $parents, $post_id );
275 }
Personally I would say that the_category
is incorrect for what you want to do, as you don’t need to display any type of parent/child relationship
You can take a look at wp_list_categories
which gives you a lot of flexibility. wp_list_categories
is also not just limited to categories, is can be used for custom taxonomies as well.
The parameter that you should have a look at here is depth
which you can set to
-
0 – All Categories and child Categories (Default).
-
1 – All Categories displayed in flat (no indent) form (overrides hierarchical).
-
1 – Show only top level Categories
-
n – Value of n (some number) specifies the depth (or level) to descend in displaying Categories
Here is a slightly modified version of the code found in the codex page. I’ve set the depth
parameter to 1
, which will only show the top most category level
<?php
$taxonomy = 'category';
// get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
// separator between links
$separator=", ";
if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {
$term_ids = implode( ',' , $post_terms );
$terms = wp_list_categories( 'title_li=&style=none&echo=0&depth=1&taxonomy=' . $taxonomy . '&include=" . $term_ids );
$terms = rtrim( trim( str_replace( "<br />', $separator, $terms ) ), $separator );
// display post categories
echo $terms;
}
?>