On Homepage “is_user_logged_in()” function is not working after login and it is working after refresh the page?

Question

I’m trying to add the menu items using filter.

Below is the full function

function new_nav_menu_items($items) {
    
    $loginLink = '<li id="menu-item-login" class="menu-item menu-item-type-post_type menu-item-object-page "><a href="'.wp_login_url().'">Login</a></li>';
    
    $resgisterLink = '<li id="menu-item-register" class="menu-item menu-item-type-custom menu-item-object-custom  top-menu-signup"><a href="javascript:void(0);" data-toggle="modal" data-target="#myModal">Subscribe</a></li>';
    
    // add the home link to the end of the menu

    if(is_user_logged_in())
    {

        global $current_user; 
        wp_get_current_user();
        //$current_user->ID;

        $user_firstname =get_user_meta($current_user->ID, 'first_name', true);

        $user_lastname =get_user_meta($current_user->ID, 'last_name', true);
        
        $editProfile = '<li id="menu-item-119" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-119 user-name"><a class="user-name-menu" href="javascript:void(0)"><i class="icon-admin-user"></i>'.$user_firstname.' '.$user_lastname.'</a>
        <ul class="sub-user-menu">
            <li><a href="'.home_url('edit-profile').'"><i class="icon-edit"></i>Edit Profile</a></li>
            <li style="margin-bottom: 10px;"><a href="'.wp_logout_url().'"><i class="icon-logout"></i>Logout</a></li>
        </ul>
        </li>';
        
        $items = $items. $editProfile;
    }
    else
    {
        $items = $items . $loginLink . $resgisterLink;
    }
    
    return $items;
}
// to handle login/logout links on the home page header menu

add_action( 'init', 'nothing_register_menus' );

function nothing_register_menus()
{
    is_user_logged_in();
    add_filter( 'wp_nav_menu_items', 'new_nav_menu_items', 10, 2 );
}

After login, “is_user_logged_in()” is always false, but after refresh the page in login state it shows login correctly.

0
Prashant Patil 4 months 0 Answers 27 views 0

Leave an answer