WordPress导航栏分类高亮问题解决方案

方法一:CSS类

/* WordPress会自动为当前菜单项添加current-menu-item类 */
.current-menu-item {
      color: #3498db;
      border-bottom: 3px solid #3498db;
      background: #f8f9fa;
}
/* 如果需要在文章页面高亮所属分类 */
.single-post .menu-item-123 {
      color: #3498db;
      border-bottom: 3px solid #3498db;
      background: #f8f9fa;
}

方法二:JavaScript

// JavaScript解决方案:检测当前分类并高亮对应菜单项
document.addEventListener('DOMContentLoaded', function() {
// 获取当前文章分类(这里需要根据实际情况调整)
var currentCategory = '科技'; // 这应该从WordPress获取


// 获取所有菜单项
var menuItems = document.querySelectorAll('.menu-item a');


// 遍历菜单项,找到匹配的分类
menuItems.forEach(function(item) {
            if (item.textContent.trim() === currentCategory) {
               item.classList.add('current-category');
                   item.parentElement.classList.add('current-category');
                       }
                  });
         });

方法三:WordPress函数

<?php
add_filter('nav_menu_css_class', 'special_nav_class_by_id', 10, 4);
function special_nav_class_by_id($classes, $item, $args, $depth) {
    if (is_single()) {
        $categories = get_the_category();
        if ($categories && $item->type === 'taxonomy' && $item->object === 'category') {
            foreach ($categories as $category) {
                // 比较菜单项对象ID(分类ID)与当前分类ID
                if ($item->object_id == $category->term_id) {
                    $classes[] = 'current-menu-item';
                    $classes[] = 'current-category-menu-item';
                    break;
                }
            }
        }
    }
    return $classes;
}
?>
THE END
喜欢就支持一下吧
点赞13赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容