Sagspot
Sagspot

Reputation: 45

How to dynamically add active class on wordpress category pages

Am new to wordpress development and I want to add an active class on my category pages. I also need the All Article to have the active class by default on load. Here's my code.

<p>
  <?php
    global $wp;
    $catURI = basename(home_url( $wp->request ));
    $activeURI = basename($_SERVER['REQUEST_URI']);
    $categories = get_categories(); ?>
      Blog categories: <a href=" <?php echo site_url(); ?>" class="cat-link <?php if ($activePage == $activeURI) echo 'active'; ?>">All Articles</a>
      <?php foreach($categories as $category) { 
        echo $catURI == $activeURI 
         ? '<a class="cat-link active" href="' . get_category_link($category->term_id) . '">' . $category->name . '</a>'
         : '<a class="cat-link" href="' . get_category_link($category->term_id) . '">' . $category->name . '</a>';
      }
  ?>
</p>

This however does not add the active class to the All Articles link and adds it to all the other category links when I click on one of them.

Any assistance will be highly appreciated.

This could sound like a repetition, but most of the solutions I've gotten seem not to solve my challenge.

Upvotes: 0

Views: 1078

Answers (1)

Sagspot
Sagspot

Reputation: 45

With the help of @ChrisHaas, I was able to get a workaround. This is the code that I finally used, and styled it accordingly.

<?php
  wp_list_categories(array(
  'show_option_all' => 'All Articles',
  'class' => 'post-category flex',
  'title_li' => 'Blog categories:'
  )); 
?> 

Upvotes: 1

Related Questions