Get Last Level Category – WordPress

Function to get all last level category ( whether it is category or subcategory )which have posts iis as follows –

Do you want to get last level category in wordpress(whether it is category or subcategory) which have posts then create the custom function defined below and call it in all categories loop –

function return_lastpostcat($categories){
$categories_temp = $categories;
foreach ( $categories_temp as $child_cat ) {
foreach ( $categories_temp as $k => $parent_cat ) {
if ( isset( $categories[ $k ] ) ) {
if ( cat_is_ancestor_of( $parent_cat, $child_cat ) ) {
unset( $categories[ $k ] );
}
}
}
}
return $categories;
}

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.