Skip to content

Instantly share code, notes, and snippets.

@habibimroncn
Created August 11, 2023 02:08
Show Gist options
  • Save habibimroncn/e21c17d0d85140936ec1c50d9eb36997 to your computer and use it in GitHub Desktop.
Save habibimroncn/e21c17d0d85140936ec1c50d9eb36997 to your computer and use it in GitHub Desktop.
Show a user's display name/user name in a WordPress menu
<?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' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment