Try it like this:
$categories = get_the_category();
echo '<ul>';
echo '<li> Parent Category: ';
foreach( $categories as $category ){
if($category->parent != 0){
$parent_category = get_term( $category->parent );
echo '<a href="' . esc_url( get_category_link($parent_category->term_id)) . '">' . esc_html($parent_category->name) . ' </a>';
break;
}
}
echo '</li>';
echo '<li>Subcategory: ';
foreach( $categories as $category ){
if($category->parent != 0){
echo '<a href="' . esc_url( get_category_link($category->term_id)) . '">' . esc_html($category->name) . ' </a>';
}
}
echo '</li></ul>';
This works pretty well if your post’s categories have the same parent category (e.g Your post has the categories ‘child_1’ and ‘child_2’ which are both children of the category ‘parent_1’). It checks each of your post’s categories. In the first foreach
-loop, as soon as a category has a parent category it will be echoed and the loop will be left because of the break
.
But if your post has multiple categories with different parent categories (e.g Your post has the category ‘child_A_1’ which is a child of ‘parent_A’, and the category ‘child_B_1’ which is a child of ‘parent_B’) this code won’t work correctly since it would only echo the parent-category of the first subcategory that occurs in the first foreach
-loop.