If post has parent add class

so I have this Issue that I cannot solve no matter what I do , thanks in advance for help :

What I am trying to do is that when I am on the post page , I give a class to the parent to its parent

I am using the following code to get the post id and its category id:

get_header();
$theCategory = get_the_category();

$categories = get_categories( array(
    'orderby' => 'name',
    'order'   => 'ASC',
    'parent' => 52,
    'hide_empty' => 0
));
$thiscat = get_queried_object_id();
$catobject = get_category($thiscat,false); // Get the Category object by the id of current category
$catobject2 = get_category($catobject,false);
$parentcat = $catobject2->category_parent; // the id of the parent category
?>
    <div class="container">
         <?php echo category_description( get_query_var( 'cat' ) ); ?>
    </div>
  <?php var_dump($thiscat) ?>

After this , if the post is in the right categoty I am trying to add a class of active here :

<?php if( $categories ): ?>
<ul class="main-categ">
  <?php foreach ( $categories as $kCat => $vCat ): ?>
    <li class="main-item <?php echo $thiscat->category_parent == $vCat->cat_ID ? 'active' : ''; ?>"><?php
                      $subCategories = get_categories( array(
                          'orderby' => 'name',
                          'order'   => 'ASC',
                          'parent' => $vCat->cat_ID,
                          'hide_empty' => 0
                      ));?>
    <a class="main-link"><?php echo $vCat->name; ?></a>
    <?php if( $subCategories ): ?>
    <ul class="subcateg">
      <?php foreach ( $subCategories as $kSub => $vSub ): ?>
      <li class="<?php echo get_query_var( 'cat' ) == $vSub->cat_ID ? 'activ':'';?>"><a href="<?php echo esc_url( get_category_link( $vSub->cat_ID ) ); ?>"><i class="fa fa-angle-double-right"></i> <?php echo $vSub->name; ?></a></li>
      <?php endforeach; ?>
    </ul>
    <?php endif; ?>
  </li>
  <?php endforeach; ?>
</ul>
<?php endif; ?>

Read more here: If post has parent add class

Leave a Reply

Your email address will not be published. Required fields are marked *