Reputation: 321
I need to display buttons for all post categories. When I click on a button, it links to the archive page of that specific category. Is there a way to highlight the current category?
My code
<div>
<?php foreach(get_categories($args) as $category) { ?>
<a href="<?php echo get_category_link($category); ?>"><?php echo $category->name; ?></a>
<?php } ?>
</div>
Upvotes: 0
Views: 921
Reputation: 35
You can try this as well.
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC'
) );
foreach( $categories as $key=>$category ) :
$catLink = get_category_link( $category->term_id );
$classactive = ( is_category( $category->name ) ) ? 'active' : '';
?>
<li class="<?=$classactive?>">
<a href="<?=$catLink?>"><?= $category->name ?>
<span><?= $category->count ?></span>
</a>
</li>
<?php endforeach; ?>
Upvotes: 0
Reputation: 169
Please try this:
<?php
$selected_category = get_queried_object();
$current_category = $selected_category->term_id;
foreach(get_categories($args) as $category) {
$selected_class = '';
if( $category->term_id == $current_category ){
$selected_class = "selected_a";
}
?>
<a href="<?php echo get_category_link($category); ?>" class="<?php echo $selected_class; ?>" ><?php echo $category->name; ?></a>
<?php
}
?>
You can then add background CSS for "selected_a" class. Thanks
Upvotes: 2