Display only deepest category on a single post?

I come to this post as i was looking for the code. But the marked answer not working for me anymore.
I have wrote a function to get the deepest level category assigned to a post.

function post_deepest_level_cat($post_categories) {
    foreach ($post_categories as $category) {
        $cat_ids[] = $category->term_id;
    }   
    $tree_args = array(
        'current_category' => $cat_ids,
        'depth'             => 50,
        'hierarchical'     => true,
        'echo' => 0,
        );                  
                
    $category_list = wp_list_categories($tree_args);                
    $dom = new DOMDocument;
    @$dom->loadHTML($category_list);
    $links = $dom->getElementsByTagName('a');
    $new_cat_array = array();
    foreach ($links as $link) { 
        $menu = get_term_by('name', $link->nodeValue, 'category');
        if (in_array($menu->term_id, $cat_ids)) {
            $deepest_cat_id = $menu->term_id;
        }                   
    }           
    return $deepest_cat_id;
}

And to use the above function here is the example.

$post_categories = wp_get_post_terms(10, 'category'); //All categories assigned to this post id "10"
$deeper_cat_id = post_deepest_level_cat($post_categories );
echo $deeper_cat_id; // will echo the id of deepest and last category of the current post.

This will help in 2020.
If you have better code let me know. Thanks

Leave a Comment