How to get current-menu-item title as variable?

This 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.

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 instead of the normal title. Simple example:

add_filter( 'single_cat_title', 'wpse16243_single_cat_title' );
function wpse16243_single_cat_title( $cat_title )
{
    if ( isset( $GLOBALS['wpse16243_title'] ) ) {
        return $GLOBALS['wpse16243_title'];
    }
    return $cat_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.

Leave a Comment