简体   繁体   中英

Need to add 'active' class to custom WordPress Navigation Menu

I am creating my own Mega Menu using the in-built navigation menu in WordPress. It works great to display different code for a standard menu item and a menu item that has a mega menu. but I want to be able to reference the active menu item and add the class active into that list item.

I am just unsure, with the following code, what I need to put where ?

// 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>";
}

[EDITED]

I know something needs to be added after this line

$classList = implode(" ", $item->classes);
echo "<li class=\"nav-item {$classList}\">";                     

Something to reference the current page

if ( [ ???? current page or current menu ???? ] 
echo "<li class=\"nav-item active {$classList}\">";

How do I reference the current page?

Or how do I add the standard WordPress classes to all menu items then I can reference that within the CSS files.


A Solution

I have found a solution.

I added this

// get the current page URL
$actual_link = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

before

// get the ID of the current nav item
$curNavItemID = $item->ID;

and then referenced it later by changing this line

echo "<li class=\"nav-item {$classList}\">";

to this

echo "<li class=\"nav-item ";
if ( $actual_link == $item->url ) {
echo 'active';
}
echo " {$classList}\">";

The 'active' class is now added to any of the menu items who's URL matches the URL of the browser window. ie: the 'current page'.

I'm sure there is a more elegant way to do this - but this seems to do what I need.

add this in your css file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM