• Resolved sayhellostranger

    (@sayhellostranger)


    Hi,
    is there a way or WP function to query an active custom menu link (a subnavigation point) with its ID in PHP? Like

    if (current_custom_link_ID == 1061) {
           echo something;
    }

    Generally speaking, I would like to track the name of the active (current) custom menu link to output it in the content area.

    In the WordPress documentation I found nothing suitable, neither with wp_nav_menu () or similar functions.

    I am grateful for every note.
    Thanx

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hello,

    Getting the currently active menu link is possible by filtering wp_nav_menu_objects, which is the easiest place to check which item is the current menu item, because WordPress already added the classes for you. The below code (Untested) should get the currently active menu item and add it as a new global variable to use where you need:

    add_filter( 'wp_nav_menu_objects', 'wpse16243_wp_nav_menu_objects' );
    function wpse16243_wp_nav_menu_objects( $sorted_menu_items )
    {
        foreach ( $sorted_menu_items as $menu_item ) {
            if ( $menu_item->current ) {
                $GLOBALS['wpse16243_title'] = $menu_item->title;
                break;
            }
        }
        return $sorted_menu_items;
    }

    You can now use this new global variable in your content, for example:

    if ( isset( $GLOBALS['wpse16243_title'] ) ) {
        return $GLOBALS['wpse16243_title'];
    }

    Of course, this only works if you display the menu before you display the title. If you need it earlier (maybe in the <title> element?), you should first render the menu and then display it later.

    ~ Steven

    Moderator bcworkz

    (@bcworkz)

    I don’t disagree with graphicscove, but just FYI, all menu items are saved as posts, as the post_type nav_menu_item. Besides what is stored in the post object, other data is stored in post meta. The menu to which an item belongs is managed by the nav_menu taxonomy. All menu items in a particular menu are assigned the same nav_menu term.

    Knowing how menus are organized will let you get a lot of particular information without the need to call wp_nav_menu(). As graphicscove pointed out, the specific HTML like classes and ids are not part of the stored menu items, they come from calling the function, so naturally calling the function is the easiest way to extract that sort of information.

    Thread Starter sayhellostranger

    (@sayhellostranger)

    hi,
    graphicscove solution works very well in my case to output this information in many different places in the template(s). thanx steven!
    nevertheless, when time I will take a closer look at the construction of post type nav_menu_item.

    thanks for your help and quick response

    mathes

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Track a Active Custom Menu Link by its ID’ is closed to new replies.