WordPress – Check if user is logged in

I am fairly new to WordPress. On my homepage I have a navigation bar which I only want to show to people who are logged in as users.

In my header.php the function is_logged_in doesn’t seem to work.

Read More

I want to place a condition in my header.php file to check if the user has logged in (and then display the navigation).

Any advice would be helpful.

Related posts

Leave a Reply

6 comments

  1. Example: Display different output depending on whether the user is logged in or not.

    <?php
    
    if ( is_user_logged_in() ) {
        echo 'Welcome, registered user!';
    } else {
        echo 'Welcome, visitor!';
    }
    
    ?>
    
  2. Try following code that worked fine for me

    global $current_user;
    get_currentuserinfo();
    

    Then, use following code to check whether user has logged in or not.

    if ($current_user->ID == '') { 
        //show nothing to user
    }
    else { 
        //write code to show menu here
    }
    
  3. This problem is from the lazy update data request of Chrome.
    At the first time you go to homepage. Chrome request with empty data. Then you go to the login page and logged in. When you back home page Chrome lazy to update the cookie data request because this domain is the same with the first time you access.
    Solution:
    Add parameter for home url. That helps Chrome realizes that this request need to update cookie to call to the server.

    add at dashboard page

    <?php 
    $track = '?track='.uniqid();
    ?>
    <a href="<?= get_home_url(). $track ?>"> <img src="/img/logo.svg"></a>
    
  4. I think that.
    When guest is launching page, but Admin is not logged in we don`t show something, for example the Chat.

    add_action('init', 'chat_status');
    
    function chat_status(){
    
        if( get_option('admin_logged') === 1) { echo "<style>.chat{display:block;}</style>";}
            else { echo "<style>.chat{display:none;}</style>";}
    
    }
    
    
    
    add_action('wp_login', function(){
    
        if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 1);
    });
    
    
    add_action('wp_logout', function(){
        if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 0);
    });