How to add the username to a custom menu

Occasionally you may wanto to add a new menu item whose label is the current username.
In the last post I showed how to build a shortcode generating this kind of data. The shortcode could be used as follow:

[userdata user_email]

By default you could not add a shortcode to generate a menu item label, as WordPress strip the brackets away.

But with a little trick you can do the magic…

Take the code I used to generate the shortcode in my last post:


// create [userdata] shortcode
function get_current_userdata_cb( $atts ){
    if ( is_user_logged_in() ) { 
        // get the current user
        $cu = wp_get_current_user();

        switch ( $atts[0] ) {
            case 'user_login':
                return $cu->user_login;
                break;
            case 'user_email':
                return $cu->user_email;
                break;
            case 'user_firstname':
                return $cu->user_firstname;
                break;
            case 'user_lastname':
                return $cu->user_lastname;
                break;
            case 'display_name':
                return $cu->display_name;
                break;
            case 'ID':
                return $cu->ID;
                break;
            default:
                return $cu->user_login;
                break;
        }

    }else{
        return '';
    }
}
add_shortcode( 'userdata', 'get_current_userdata_cb' );

Now that the shortcode is available, you’ll call the same function to generate dinamically the label of your custom menu item:


/**
 * Build custom menu item's title
 *
 * @param WP_Post[] $menu_items
 *
 * @return WP_Post[]
 */
function my_dynamic_menu_items( $menu_items ) {
    
    $sc_atts = array( '#user_login#', '#user_email#', '#user_firstname#', '#user_lastname#', '#display_name#', '#ID#' );

    foreach ( $menu_items as $menu_item ) {

        if ( in_array( $menu_item->title, $sc_atts )){

            global $shortcode_tags;

            if ( isset( $shortcode_tags['userdata'] ) ) {

                $user = do_shortcode( '[userdata ' . str_replace( '#', '', $menu_item->title ) . ']' );
                $menu_item->title = $user;
            }
        }
    }

    return $menu_items;
}
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );

The callback my_dynamic_menu_items accepts as argument an array with all menu items stored in WP database.
The elements of $sc_atts are the strings you should use as labels of the menu items. You will save these strings in Appearence – Menu page of your WordPress install. The string set the particular data you’ll want to retrieve from the database.

The foreach cycle iterates among all menu items, and the following condition tests whether the string has a pair in $sc_atts.

In this case, do_shortcode executes the callback and outputs the label.

shortcode menu title