0

I have a custom category buttons which each of buttons link and echoed the specific category at the same page. my goal is to put a active background hover color on the active link. here is my code so far:

<?php
  $args = array(
  'orderby' => 'slug',
  'order' => 'ASC',
  'parent' => 0,
  'hide_empty' => false
   );
  $categories = get_categories( $args );
  foreach( $categories as $category ){
  echo '<li><a class="ctg" href="' . get_category_link( $category->term_id ) .' ">' . $category->name . '</a></li>';
   }
   ?>

and my css:

    .ctg:hover {
      background: #A6EBF2;
    }
    .ctg:active {
      background-color: #A6EBF2;
    }

any help is appreciated.


here is the code I made so far:

$categories = get_categories( $args );
             foreach( $categories as $category ){
             $the_category_id = $category->term_id;
             if(function_exists('rl_color')){
                 $rl_category_color = rl_color($the_category_id);
             } else {
                 $rl_category_color = '#a6ebf2'; // bg color
              }
              echo '<li><a href="'. get_category_link( $category->term_id ) .'"  class="' . $category->slug . '" title="View all posts in '. esc_attr($category->name) . '" style="background-color:' . $rl_category_color .' ">' . $category->name . '</a></li>';
             
1
  • Where are you displaying these category links? On the site footer, a single post, on every page, the category archive? This context relates to how you determine, which of the category links should have the active class. Commented May 12, 2021 at 10:51

1 Answer 1

1

The :active is a selector for changing a link when clicked to show the act of clicking something. It causes some confusion when they called it "active"!

You need to add an .active class to show the current active element and style this differently.

Also, you can combine CSS with a comma

a.ctg:hover, 
.active {
  background: #A6EBF2;
}

Then you'll need some code for adding the .active to the active item, see the following:

Highlight Current Page in WordPress 3.0 Menus

Adding .active class to active menu item

1
  • Hi @Johm I tried and applied the sample codes at the provided links, but it seems the different to my situation. I got the idea about putting a class on the echoed categories but the problem is all the categories now have background color. I wanted is only the active category have a background color. Commented May 5, 2021 at 10:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.