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):
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