treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] WordPress: Add a class on an li for "current category"

  • 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 <li> that contains the anchor for the currently displaying category page. What's the best way to do this?

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

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

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

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

  • 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.