When building custom WordPress themes, you often need to display not just the current category, but also its parent category (for breadcrumb navigation or hierarchical menus).
Learn more about professional WordPress development at WPPoland.
WordPress stores categories in a hierarchical structure, but get_the_category() returns a flat array. Here’s how to extract the hierarchy.
Method: Get_the_category() + parent check
Here’s a ready-made function you can paste into functions.php:
function wppoland_get_category_hierarchy() {
$categories = get_the_category();
if ( empty( $categories ) ) {
return false;
}
// Get the first category
$category = $categories[0];
$output = '';
// If category has a parent
if ( $category->parent ) {
$parent = get_category( $category->parent );
$output .= '<a href="' . esc_url( get_category_link( $parent->term_id ) ) . '">' . esc_html( $parent->name ) . '</a> » ';
}
// Current category
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a>';
return $output;
}
Usage IN template
<?php
$hierarchy = wppoland_get_category_hierarchy();
if ( $hierarchy ) {
echo '<div class="category-breadcrumb">' . $hierarchy . '</div>';
}
?>
This will output something like: Technology » WordPress
Alternative: Full breadcrumb trail
If you need the complete hierarchy (grandparent, parent, child), use this recursive approach:
function wppoland_get_full_category_trail( $category_id ) {
$trail = array();
while ( $category_id ) {
$category = get_category( $category_id );
array_unshift( $trail, $category );
$category_id = $category->parent;
}
$output = '';
foreach ( $trail as $cat ) {
$output .= '<a href="' . esc_url( get_category_link( $cat->term_id ) ) . '">' . esc_html( $cat->name ) . '</a> » ';
}
return rtrim( $output, ' » ' );
}
This solution is clean, efficient, and handles multi-level category hierarchies properly.


