herrfischer
herrfischer

Reputation: 1828

Foreach-loop - check if category is in sub-category of category

I have a foreach loop (wordpress template) that lists all the categories of the post except the "top news" category:

<?php
    $exclude = array("Top News");
    $catagorystring = '';
    foreach((get_the_category()) as $category) {
        if ( !in_array($category->cat_name, $exclude) ) {
            $catagorystring .= '<a href="'.get_category_link($category->term_id ).get_option('category_base').'" class="category-link-einrichtungen">' . $category->name . '</a>, ';
        }
    }
    echo substr($catagorystring, 0, strrpos($catagorystring, ','));
?>

That works but in additional i want to hide child-categories of "top news", too.

There is a wordpress function that allows me to do something like this:

<?php if(post_is_in_descendant_category('3') ) { 
    echo 'is in category 3';
} ?>

But i have no idea how to get this into the foreach loop.

Upvotes: 0

Views: 1965

Answers (1)

vard
vard

Reputation: 4136

You can use the parent property of the category object and check it against any id of the categories in the exclude array:

$excludedCategories = array();
foreach((get_the_category()) as $category) {
  $breakLoop = false;
  if (!in_array($category->cat_name, $exclude)) {
    foreach($exclude as $cat_name_to_exclude) {
      if($category->parent == get_cat_ID($cat_name_to_exclude)) {
        $breakLoop = true;
      }
    }
    if($breakLoop) {
      array_push($excludedCategories, $category);
      continue;
    }
    $categorystring .= '<a href="'.get_category_link($category->term_id ).get_option('category_base').'" class="category-link-einrichtungen">' . $category->name . '</a>, ';
  }
}

Upvotes: 1

Related Questions