0

I'm trying to display a post category, I have two categories with two different parents.

I want to show only one of the category according to the parent category. This is the code that I am using at the moment to get the posts category.

$categories = get_the_category();
echo '<span class="parentCat">more from ';
foreach ( $categories as $category ) {
    echo '<a href="/#'. $category->slug .'"><strong>' .$category->cat_name. '</strong></a>';
}
echo '</span>';

Thank you very much

2 Answers 2

1

You can modify your code like this to display only one category according to the parent category:

$categories = get_the_category();
$parent_cat_id = 123; // Replace with your parent category ID
echo '<span class="parentCat">more from ';
foreach ( $categories as $category ) {
    if ($category->category_parent == $parent_cat_id) {
        echo '<a href="/#'. $category->slug .'"><strong>' .$category->cat_name. '</strong></a>';
        break; // Stops the loop after finding the first matching category
    }
}
echo '</span>';
0

You can use get_categories if you know parent category id.

$categories = get_categories( array(
    'parent'  => $parent_id
) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.