This WordPress code snippet is designed to dynamically insert the current user’s display name into your website’s navigation menus. To make this work, you need to include a specific placeholder {{username}}
in the titles of your menu items where you want the user’s name to appear. The code searches for this placeholder in each menu item and replaces it with the logged-in user’s display name.
If the user is not logged in or does not have a display name, the placeholder will be removed, leaving that part of the menu item title blank. This functionality is ideal for creating a more personalized and welcoming user experience, like greeting users by their name directly in the menu
function snn_display_username_in_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. $username = $current_user->display_name ? $current_user->display_name : ''; $menu_item->title = str_replace( '{{username}}', $username, $menu_item->title ); } } return $menu_items; } add_filter( 'wp_nav_menu_objects', 'snn_display_username_in_menu' );