I am new to WordPress
I am setting up wordpress Site which has 3 Menus
- Top menu
- Header Menu
- Footer Menu
My issue is I need to add the User name to My Top menu Only when User is Logged in
But using below Code snippet it adds the Custom menu Item in all the Menus the Below Code i found while googleing the Solution for the above Query
function my_custom_menu_item($items)
{
if(is_user_logged_in())
{
$user=wp_get_current_user();
$name=$user->display_name; // or user_login , user_firstname, user_lastname
$items .= '<li><a href="">Welcome '.$name.'</a></li>';
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
This is my Top menu Structure
if User is not logged in
- My Account
- Login
- Signup
- Lost Password
if User is Logged In
- Welcome Nikhil
- Profile
- Change Password
- Logout
- blogs
wp_nav_menu_items
filters passes menu arguments as second parameter.So if you modify code to this:
You will be able to check data
$args
inside function to match specific menu. However the specifics of what to check for depend on how precisely your menus are set up. Might be$args['menu']
holding name, might be$args['theme_location']
, etc.Another option is to simply add your callback right before the needed menu is called and remove right after in theme template:
@Rarst is right, you need the second argument to do this only for an specific menu, in your example will be something like: