首页 > 解决方案 > 需要将“活动”类添加到自定义 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 匹配的任何菜单项中。即:“当前页面”。

我确信有一种更优雅的方法可以做到这一点 - 但这似乎可以满足我的需要。

标签: phpwordpressmenubootstrap-4navigation

解决方案


将此添加到您的 css 文件中

ul.nav-menu li.current-menu-item > a {
    color: #f7931d !important;
}
li.current-menu-parent >a, .current-menu-item >a {
    color: #f7931d !important;
}


推荐阅读