Finding active menu item in menu

So thought I would rewrite the menu generator to reorder the menu based on where the user is, and I figured out a way to move it around, it is relatively crude way.

But my issue is, how can I find name or ID of the current active option.

The below example uses a hardcoded value ($current_id) to identify what to put in the middle, but I want to get the ID of current page.

This is the core to reorder the list

    $menuLocations = get_nav_menu_locations(); // Get our nav locations (set in our theme, usually functions.php)
                                               // This returns an array of menu locations ([LOCATION_NAME] = MENU_ID);

//    foreach ( $menuLocations as $menuLocation ) {
//      echo '<p style="color: red">',$menuLocation,'</p>';

//     }
//     print_r(array_keys($menuLocations));

    $menuID = $menuLocations['primary_navigation']; // Get the *primary* menu ID
    $primaryNav = wp_get_nav_menu_items($menuID); // Get the array of wp objects, the nav items for our queried location.

//print_r(array_keys($primaryNav));



    $current_id = 5;
    $menu_length = count($primaryNav);
    if ( '5' == $menu_length ){
        echo $MenuStart;
        for ($i = 0 ; $i <=4 ; $i++) {
            $cu_target = $i + $current_id + 3;
            if ($cu_target > 5 ) {
              $cu_target -= 5;
            }
            if ($cu_target > 5 ) {
               $cu_target -= 5;
            }
            $navItem = $primaryNav[$cu_target - 1];
            echo '<li class="MainNavLink',$i,' nav-item">';
            echo '<a class="nav-link py-1 pr-3" href="'.$navItem->url.'" title="'.$navItem->title.'">'.$navItem->title.'</a>';
            echo '</li>';
        }

Read more here: Finding active menu item in menu

Leave a Reply

Your email address will not be published. Required fields are marked *