Wordpress find deepest category
// get all post categories
$postCats = wp_get_post_terms($post->ID, 'category');
// filter categories and find one on deepest level
$deepest = array_filter($postCats, function($cat) {
// static variable with number of parent categories
static $parents = 0;
// get number of parent categories
$parentCategories = count(get_ancestors($cat->term_id, 'category'));
// if found category with more parents than previous = we are on deeper level
if ($parentCategories > $parents) {
// store for futher iterations
$parents = $parentCategories;
return true;
}
return false;
});