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

Leave a Comment