How to show only last child categories using the_category()

Have you ever wanted to change the_category()‘s behaviour so that it’ll only show the leaves (last child categories) of the selected WordPress categories?

For example, you might have a category hierarchy of Food > Cat > Prescription Cat Food, and it doesn’t really make sense to show all three categories. Due to organizational reasons however, you need to have all three of them selected. How do you force your theme then, to only display the Prescription Cat Food category?

It’s quite easy actually. Just paste the following code in your functions.php file (preferably of a child theme):

add_filter( 'the_category_list', 'ci_theme_the_category_list_remove_parent_categories', 10 );
function ci_theme_the_category_list_remove_parent_categories( $categories ) {
	$categories_tmp = $categories;
	foreach ( $categories_tmp as $child_cat ) {
		foreach ( $categories_tmp as $key => $parent_cat ) {
			if ( isset( $categories[ $key ] ) ) {
				if ( cat_is_ancestor_of( $parent_cat, $child_cat ) ) {
					unset( $categories[ $key ] );
				}
			}
		}
	}

	return $categories;
}

All this code does, is to go through each combination of (the selected) categories unconditionally, and check whether one is an ancestor of the other. If it is, the ancestor is removed from the list of the returned categories. Go through all possible combinations, and you’re left with all the child categories that don’t have any selected child categories themselves.

Drop a quick comment if you found it useful. :D

Leave a Reply

Your email address will not be published. Required fields are marked *