Get Last Level Category – WordPress

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;
}

Leave a Reply

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