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

问题描述 投票:0回答:1

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

我的代码

<div>
    <?php foreach(get_categories($args) as $category) { ?>
            <a href="<?php echo get_category_link($category); ?>"><?php echo $category->name; ?></a>
    <?php } ?>
</div>
php wordpress categories
1个回答
0
投票

请尝试以下方法:

<?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”类添加背景CSS。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.