【问题标题】:Need to add 'active' class to custom WordPress Navigation Menu需要将“活动”类添加到自定义 WordPress 导航菜单
【发布时间】:2019-11-09 22:41:53
【问题描述】:

我正在使用 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 匹配的任何菜单项。即:“当前页面”。

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

【问题讨论】:

    标签: php wordpress menu bootstrap-4 navigation


    【解决方案1】:

    将此添加到您的 css 文件中

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

    【讨论】:

    • 这不起作用,因为生成的代码不会在列表项中创建标准的 WordPress 菜单类,只是“导航项”以及在 WordPress 外观 > 菜单部分中添加的任何额外类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多