how to add Custom menu item like User name in Header Menu only

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

Read More

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

Related posts

2 comments

  1. wp_nav_menu_items filters passes menu arguments as second parameter.

    So if you modify code to this:

    add_filter( 'wp_nav_menu_items', 'my_custom_menu_item', 10, 2);
    
    function my_custom_menu_item($items, $args) ...
    

    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:

    add_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
    
    // target wp_nav_menu() call in between
    
    remove_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
    
  2. @Rarst is right, you need the second argument to do this only for an specific menu, in your example will be something like:

    function my_custom_menu_item($items, $args)
    {
        if(is_user_logged_in() && $args->theme_location == 'primary')
        {
            $user=wp_get_current_user();
            $name=$user->display_name; // or user_login , user_firstname, user_lastname
            $items .= '<li><a href="">Welcome '.$name.'</a></li>';
            $items.= //Change Password, Logout, etc
        }
        elseif (!is_user_logged_in() && $args->theme_location == 'primary') {
            $items .= '<li><a href="'. site_url('wp-login.php') .'">Log In</a></li>';
            $items.= //Sign up, Lost Password
        }
        return $items;
    }
    add_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
    

Comments are closed.