In this guide, we will cover how to display a user’s name in a WordPress menu. This will require a bit of knowledge with working with code snippets and general shortcodes in WordPress.

This solution will create a custom shortcode or variable, {{username}} to be inserted in any WordPress menu and then replace this variable with the user’s actual display name. This is great if you want to create a meta menu that points to a user’s profile page of some sort that says “Welcome admin“.

Example of Welcome {{username}}, on frontend of a WordPress site.

To add a custom code snippet to our WordPress site, without worrying about losing functionality in WordPress you may follow this guide.

<?php
/**
  * Show a user's display name/user name in a WordPress menu.
  * Once this code is added to your site, you may add {{username}} to the link text.
  * Follow this guide to add code to your WordPress site - https://yoohooplugins.com/customize-wordpress/
  *
  * Full guide here - https://yoohooplugins.com/display-username-wordpress-menu/
  */
function yh_display_username_wp_menu( $menu_items ) {
    global $current_user;
    foreach ( $menu_items as $menu_item ) {
        if ( strpos( $menu_item->title, '{{username}}' ) !== false ) {
            // Get username, otherwise set it to blank.
            if ( $current_user->display_name ) {
                $username = $current_user->display_name;
            } else {
                $username = '';
            }
                $menu_item->title =  str_replace( '{{username}}',  $username, $menu_item->title );
        }
    }
    return $menu_items;
}
add_filter( 'wp_nav_menu_objects', 'yh_display_username_wp_menu' );

Once the code snippet is added, it will replace the variable {{username}} with the user’s display name. To add this variable to your WordPress menu please take the following steps:

  1. Login to your WordPress dashboard.
  2. Navigate to Appearance and select Menus.
  3. Choose your menu you would like to add the username to.
  4. Find or add a menu item you would like to show the username in and click on the dropdown arrow.
  5. Edit the Link Text and add {{username}}
  6. Save your menu.
  7. Repeat this for each menu you would like to show the username in.
Example how to add {{username}} to WordPress menu.
Example how to add {{username}} to WordPress menu.

If you have any questions or feedback regarding this code snippet, please don’t hesitate to leave a comment below.

Photo by Adam Solomon on Unsplash | Code reference taken from (and altered): https://wordpress.stackexchange.com/questions/196453/displaying-logged-in-user-name-in-wordpress-menu

Stay in the loop!

15% off your next purchase, just for you 🎁

Sign up to receive your exclusive discount, and keep up to date on our latest news, products & offers!

We don’t spam, ever! Read our privacy policy for more info.