列出类别并突出显示当前类别存档页面

List categories and highlight current category archive page

我需要显示所有 post 类别的按钮。当我点击一个按钮时,它会链接到该特定类别的存档页面。有没有办法突出显示当前类别?

我的代码

<div>
    <?php foreach(get_categories($args) as $category) { ?>
            <a href="<?php echo get_category_link($category); ?>"><?php echo $category->name; ?></a>
    <?php } ?>
</div>

请试试这个:

<?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 
} 
?>

然后您可以为 "selected_a" class 添加背景 CSS。谢谢