Wordpress - Displaying Logged-In User Name in Wordpress Menu

Okay, I found a solution (and it can be used for any theme, with any plugin as it only uses core WordPress functions).

In the menu, name the menu item where you want the user's name to appear with a place-holder (see screenshot below). Example: #profile_name#, #user#, #random#

enter image description here

Now, add the following code to the your child-theme's functions.php:

function give_profile_name($atts){
    $user=wp_get_current_user();
    $name=$user->user_firstname; 
    return $name;
}

add_shortcode('profile_name', 'give_profile_name');

add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
    foreach ( $menu_items as $menu_item ) {
        if ( '#profile_name#' == $menu_item->title ) {
            global $shortcode_tags;
            if ( isset( $shortcode_tags['profile_name'] ) ) {
                // Or do_shortcode(), if you must.
                $menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
            }    
        }
    }

    return $menu_items;
} 

In case you're using your own place-holder, remember to replace #profile_name# with the name of your custom place-holder in the code above.

Apologies in case I've misused the term 'place-holder'.


The code:

function give_profile_name($atts){
...
}

gives a warning. Better is:

function give_profile_name(){
...
}

And it is better to detect if the user is logged in or not. Like so:

function give_profile_name(){
    $user=wp_get_current_user();
    if(!is_user_logged_in())
        $name = "User not logged in";
    else
         $name=$user->user_firstname.' '.$user->user_lastname; 
    return $name;
}

Hope this helps.


No shortcode needed

add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
    foreach ( $menu_items as $menu_item ) {
        if ( strpos($menu_item->title, '#profile_name#') !== false) {
                $menu_item->title =  str_replace("#profile_name#",  wp_get_current_user()->user_firstname, $menu_item->title);
        }
    }

    return $menu_items;
}