简体   繁体   中英

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.

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:'
  )); 
?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM