Skip to content
Advertisement

List categories and highlight current category archive page

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>

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement