admin管理员组

文章数量:1122846

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

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

Share Improve this question edited Jan 31, 2017 at 12:35 CodeMascot 4,5372 gold badges15 silver badges25 bronze badges asked Jan 31, 2017 at 12:28 Yaron WainbergYaron Wainberg 1
Add a comment  | 

2 Answers 2

Reset to default 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>';

You can use get_categories if you know parent category id.

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

本文标签: post categorieshow to show only categories with a specific parent id