You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据状态设置WordPress链接样式:高亮当前活动链接

解决Elementor超级菜单当前页面链接高亮问题

我使用Elementor超级菜单配置了指向不同产品页面的自定义文本链接,希望当前所在页面的活动链接呈现不同样式,但WordPress没有简便的设置选项。需求是当页面中的链接与当前URL匹配时,通过CSS将其高亮显示,尝试了以下代码但未能生效:

function highlight_current_page_link() { ?>
    <style>
    .current-page-link {
        /* Change the style of the current page link here */
        font-weight: bold;
        text-decoration: underline;
    }
    </style>
    <script>
    jQuery(document).ready(function() {
        var currentURL = window.location.href;
        jQuery(&quot;a&quot;).each(function() {
            var linkURL = jQuery(this).attr(&quot;href&quot;);
            if (linkURL == currentURL) {
                jQuery(this).addClass(&quot;current-page-link&quot;);
            }
        });
    });
    </script>
<?php }
add_action('wp_head', 'highlight_current_page_link');

问题分析

原代码失效的原因主要有几点:

  • 代码中使用了转义引号&quot;,前端解析时会引发jQuery语法错误
  • 直接匹配完整URL,未处理末尾斜杠、查询参数等格式差异,比如example.com/product和example.com/product/?param=1会被判定为不匹配
  • 选择器范围过大,遍历页面所有<a>标签,易与其他元素冲突,且样式优先级不足

修正后的代码

function highlight_current_page_link() { ?>
    <style>
    .elementor-nav-menu .current-page-link {
        font-weight: bold;
        text-decoration: underline;
        color: #ff4444; /* 自定义高亮颜色 */
    }
    </style>
    <script>
    jQuery(document).ready(function($) {
        // 标准化当前URL:移除末尾斜杠和查询参数
        var currentURL = window.location.href.replace(/\/$/, '').split('?')[0];
        
        // 仅针对Elementor超级菜单的链接进行处理
        $('.elementor-nav-menu a').each(function() {
            var linkURL = $(this).attr('href');
            if (!linkURL) return;
            
            // 标准化链接URL,和当前URL格式统一
            linkURL = linkURL.replace(/\/$/, '').split('?')[0];
            
            // 匹配时添加高亮类
            if (linkURL === currentURL) {
                $(this).addClass('current-page-link');
            }
        });
    });
    </script>
<?php }
add_action('wp_head', 'highlight_current_page_link');

关键修改说明

  • 替换转义引号为普通引号,修复jQuery语法错误
  • 限定选择器为.elementor-nav-menu a,仅处理超级菜单内的链接,避免全局影响
  • 标准化URL格式,移除末尾斜杠和查询参数,解决URL格式差异导致的匹配失败
  • 增加CSS选择器前缀.elementor-nav-menu,提高样式优先级,避免被Elementor默认样式覆盖
  • 添加空链接判断,防止控制台报错

额外注意事项

  • 如果你的Elementor超级菜单容器类不是.elementor-nav-menu,可以通过浏览器开发者工具查看菜单父元素的类名,替换代码中对应的选择器
  • 可根据需求调整.current-page-link的CSS样式,比如添加背景色、边框等
  • 确保WordPress已加载jQuery(Elementor默认会加载,若手动禁用需重新启用)

内容的提问来源于stack exchange,提问作者LastHerd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:52:40