Grow your CSS skills. Land your dream job.

WordPress: Add a class on an li for “current category”

  • # February 27, 2013 at 6:45 pm

    Hi-
    Currently I’m using this code in WordPress to display a string of breadcrumbs (Link / Link / Link) across the top of my archive pages via twitter Bootstrap.

    < ?php
    $cat_arguments = array(
    ‘orderby’ => ‘name’,
    ‘parent’ => 0
    );
    $cats = get_categories($cat_arguments);
    $i = 0;
    foreach($cats as $category) {
    echo ‘<li><a href=”‘.get_category_link( $category->term_id ).'”>’.$category->name.'</a>';
    $i++;
    if ($i < count($cats)) {
    echo ‘/‘;
    }
    }
    ?>
    However, I want to add a `class=”current-category”` to the `

  • ` that contains the anchor for the currently displaying category page. What’s the best way to do this?
# February 28, 2013 at 4:22 pm

After experimenting for several hours, I was able to find something that worked.

# February 28, 2013 at 5:19 pm

Can you share your solution, so other people can get some ideas if they run into similar issues.

# March 8, 2013 at 8:44 pm

I would, but unfortunately, I’m having trouble dealing with having to escape the <> symbols. =(

# March 8, 2013 at 9:01 pm

You could create CodePen, in the HTML section just comment out any php code, like so http://codepen.io/anon/pen/rybqo

# March 13, 2013 at 12:56 am

Ok, so here’s what I was able to come up with. Basically using WP’s conditional tags, I created an IF statement that checked to see if the current category was not equal to the ID of the current category. Therefore, if there was a match for ID’s, we could then run a separate line where we added a class to the current category.

Here’s the [pen](http://codepen.io/anon/pen/LCHFJ “codepen!”).

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".