php - 需要将“活动”类添加到自定义 WordPress 导航菜单
问题描述
我正在使用 WordPress 中的内置导航菜单创建自己的超级菜单。为标准菜单项和具有大型菜单的菜单项显示不同的代码非常有用。但我希望能够引用活动菜单项并将活动类添加到该列表项中。
我只是不确定,使用以下代码,我需要把什么放在哪里?
// if there are items in the primary menu
if ( $items = wp_get_nav_menu_items( $menu->name ) ) {
// loop through all menu items to display their content
foreach ( $items as $item ) {
// if the current item is not a top level item, skip it
if ($item->menu_item_parent != 0) {
continue;
}
// get the ID of the current nav item
$curNavItemID = $item->ID;
// get the custom classes for the item
// (determined within the WordPress Appearance > Menu section)
$classList = implode(" ", $item->classes);
echo "<li class=\"nav-item {$classList}\">";
if ( in_array('has-mega-menu', $item->classes)) {
echo "<a class=\"nav-link dropdown-toggle\" href=\"{$item->url}\" id=\"navbarDropdown\" role=\"button\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\">{$item->title}</a>\n";
}
else {
echo "<a class=\"nav-link\" href=\"{$item->url}\">{$item->title}</a>";
}
[编辑]
我知道在这一行之后需要添加一些东西
$classList = implode(" ", $item->classes);
echo "<li class=\"nav-item {$classList}\">";
引用当前页面的内容
if ( [ ???? current page or current menu ???? ]
echo "<li class=\"nav-item active {$classList}\">";
如何引用当前页面?
或者如何将标准 WordPress 类添加到所有菜单项,然后我可以在 CSS 文件中引用它。
一个解法
我找到了解决方案。
我添加了这个
// get the current page URL
$actual_link = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
前
// get the ID of the current nav item
$curNavItemID = $item->ID;
然后通过更改此行来引用它
echo "<li class=\"nav-item {$classList}\">";
对此
echo "<li class=\"nav-item ";
if ( $actual_link == $item->url ) {
echo 'active';
}
echo " {$classList}\">";
'active' 类现在被添加到 URL 与浏览器窗口的 URL 匹配的任何菜单项中。即:“当前页面”。
我确信有一种更优雅的方法可以做到这一点 - 但这似乎可以满足我的需要。
解决方案
将此添加到您的 css 文件中
ul.nav-menu li.current-menu-item > a {
color: #f7931d !important;
}
li.current-menu-parent >a, .current-menu-item >a {
color: #f7931d !important;
}
推荐阅读
- oracle11g - ORA-12154: TNS: 无法解析 Visual Studio 2017 中指定的连接标识符
- powerbi - 如何在 Power BI 中按自定义日期层次结构按时间顺序对图表进行排序
- javascript - 基于 className 动态添加事件处理程序
- python - Django:为具有多个评分标准的评论网站生成评分平均值
- javascript - 使用构造函数创建对象时,公共成员如何能够访问私有成员?- JavaScript
- react-native - 如何解决 cocoapods 中继 CDN 问题?
- jenkins - 如何在 Jenkins 中使用 windows 平台配置 Git
- r - 两个图的链式生成
- slack - SLACK - 读取频道中的最后一张图片 - 获取它的 URL 并通过 Slack APP 将其发送到 API
- regex - 正则表达式按特定值拆分字符串