Quick Tip: Displaying the current user’s username in UberMenu

UberMenu allows you to place any shortcode content inside your menu, so adding custom content becomes as simple as writing a shortcode to return that content.

In this example, we’ll grab the current user’s username and display it in the menu.

Write the shortcode

First we want to create a simple shortcode which we will call like this in the menu: [current-username]. We’ll use WordPress’s core wp_get_current_user() function to retrieve the current user object and then return the user’s display name.

add_shortcode( 'current-username' , 'ss_get_current_username' );
function ss_get_current_username(){
	$user = wp_get_current_user();
	return $user->display_name;
}

This PHP can be added to the theme’s functions.php, preferably in a child theme to preserve changes more easily.

For a more detailed explanation of writing custom shortcodes, see How to write a custom shortcode for UberMenu.

Add the shortcode to the menu

You can create the username menu item with whichever type of menu item you prefer. In this example, we’ll create a new custom menu item ( “Link” ) to hold our username menu item. Set the URL to # and the link text to “Username” (temporarily) and add it to the menu.

Next, replace the Navigation Label with our new shortcode, [current-username] and save the menu

Finally, tell the menu to allow shortcodes in Navigation Labels via the UberMenu Control Panel

UberMenu 3

Main UberMenu Configuration > Miscellaneous > Allow Shortcodes in Navigation Label & Description

UberMenu 2

Descriptions, Shortcodes, Widgets > Advanced Content Capabilities > Allow Shortcodes in Navigation Label & Description

Now your menu will display the current user’s username inside the menu

Next Steps

The above strategy will display the username of the currently logged in user. When the user is logged out, the menu item will be blank. You could adjust the shortcode to return something else when logged out. Alternatively, you could use the UberMenu Conditionals Extension to hide the menu item entirely when the user is logged out, and replace it with a different item, perhaps a login link. To do so, you would create two menu items: one for the logged in user (displaying the username), and one for the logged out user (displaying a login link). You would apply the “If user is logged in” condition to the first, and “If user is not logged in” condition to the second.

Learn more about the UberMenu Conditionals Extension

Leave a Reply

Your email address will not be published. Required fields are marked *