0

Some of my categories have parent categories, and some don't. What I need is a way to show only categories without parent, and child categories.

So for instance I have

Cat 1
Cat 2 
Cat 3
 - Cat 3.1
 - Cat 3.2
Cat 4
Cat 5

And my post has Cat 1, Cat 3and Cat 3.1 on it (permalink reasons - I need to set the parent category as well). With this:

$category_out=array();
$categories = get_the_category();
foreach ($categories as $category_one) {
    $category_out[] ='<a class="' .$category_one->slug.'" href="'.esc_url( get_category_link( $category_one->term_id ) ).'">' .$category_one->name.'</a>';
}
$category_out = implode( '', $category_out);

I will get out in my $category_out Cat 1, Cat 3 and Cat 3.1. And I don't wan't Cat 3 to be in the list.

I tried with

$category_out=array();
$categories = get_the_category();
foreach ($categories as $category_one) {
    if ($category_one->category_parent != 0) {
        $category_out[] ='<a class="' .$category_one->slug.'" href="'.esc_url( get_category_link( $category_one->term_id ) ).'">' .$category_one->name.'</a>'
    }
}
$category_out = implode( '', $category_out);

But this shows only Cat 3.1 since, technically, Cat 1-5 are all parent categories to themselves.

Is there a way to show only subcategories of existing parent category and other non parent-child related categories in a category list?

Thanks.

1 Answer 1

0

you can use get_term_children to achieve this !

The loop :

foreach ($categories as $category_one) {
    if (empty(get_term_children($category_one->term_id,$category_one->taxonomy))){
    $category_out[] ='<a class="' .$category_one->slug.'" href="'.esc_url( get_category_link( $category_one->term_id ) ).'">' .$category_one->name.'</a>';
    }
}

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.