E
E
Evgeniy2021-08-06 13:37:13
WordPress
Evgeniy, 2021-08-06 13:37:13

How to add a class to an element of the current WordPress category?

Good afternoon
Help me please, otherwise I'm slowing down

The usual code that displays the categories of the store in the a tag and the number of products in it
Displayed on the general page of the store and in the categories

Tell me how to add the "current-cat" class to the current category?
For example, if you moved to the "food" category so that one of the links could be highlighted.

I think for example:
Get the current title of the category page:

$current_cat = $category_title = single_term_title('', 0);


and then we compare it with the one in the a tag,
or it's not there anymore .. confused

How to write the condition correctly?

<div class="categories">
  <?php $product_categories = get_terms(array( 'taxonomy' => 'product_cat', 'hide_empty' => true) );
  
      if( $product_categories ) : ?>
        <?php foreach( $product_categories as $product_category ) : ?> 
        
          <a href="<?php echo get_term_link( $product_category ) ?>">
            <?php echo $product_category->name ?>
            <span><?php echo $product_category->count ?></span> 
          </a>
          
        <?php endforeach; ?>
      <?php endif; ?>
</div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yarovikov, 2021-08-06
@Zheleznov

echo is_tax() && get_queried_object()->slug === $product_category->slug ? 'current' : '';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question