0

On Wp Forums, I found a code that shows categories with images and it works very well. But I couldn't figure out how to highlight current category on category.php and single.php

Here is the code that i'm using

$cats = get_categories('hide_empty=0&child_of=2&orderby=count&number=99&order=asc');
foreach ((array)$cats as $cat) {
$catdesc = $cat->category_description;
echo '<a href="' . get_category_link($cat) . '" title="'. strip_tags($catdesc) .'">
        <li>
          <img src="' . get_home_url () . '/wp-content/uploads/' . $cat->slug. '.jpg" alt="' . $cat->cat_name . '" class="front-img" />
        </li>
      </a>';
}

1 Answer 1

1

You can do something like

    <?php
        $current_category = get_the_category();
        /* 
           $current_category[0]->ID is holding the current category now. 
           If there are more than 1 categories for the post you should iterate
           through all of them and check if the current category you're 
           displaying is in there
        */

        $cats = get_categories('hide_empty=0&child_of=2&orderby=count&number=99&order=asc');
        foreach ((array)$cats as $cat) {
            $catdesc = $cat->category_description;
            ?>
            <li class="<?php echo ( ( $current_category[0]->ID === $cat->ID )? 'current' : '' ); ?>">
                <a href="<?php echo get_category_link($cat); ?>" title="<?php echo strip_tags($catdesc); ?>">
                    <img src="<?php echo get_home_url (); ?>/wp-content/uploads/<?php echo $cat->slug ?>" alt="<?php echo $cat->cat_name; ?>" class="front-img">
                </a>
            </li>
        <?php } ?>
4
  • I'm getting error on this line, what is the problem? <li class="<?php echo ( $current_category[0]->ID === $cat->ID )? 'current' : '' ); ?>"> it says Parse error: syntax error, unexpected ')', expecting ',' or ';' in
    – Omur U
    Commented Jan 24, 2014 at 19:45
  • I'll cross check and will let you know Commented Jan 24, 2014 at 19:47
  • Edited it. I was missing a openning '(' Commented Jan 24, 2014 at 19:48
  • Thanks Nickolay, now code works! But it puts "current" class to every list item. I tried in single.php and category.php No luck.. here is the link bit.ly/1jKzCDa
    – Omur U
    Commented Jan 24, 2014 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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