【发布时间】: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