if(!is_user_logged_in()) returns true when 404

I’m running a closed website for registered users only.

For doing so I check in if user is logged in

Read More
// no non-authenticated users allowed
if( !is_user_logged_in() ) {
    wp_redirect('/wp-login.php');
    //auth_redirect();
    exit;
}

But sometimes It just logged me out, and I could not understand where to seek the problem. it happened ocassionally and so it was really hard to debug.

Now: with different function I found that if( !is_user_logged_in() ) returns true on 404 page.

I’m still debugging but I want to hear your opinion, is this normal or intended? Could you confirm if this is same with your installaton? I’m running latest version of WordPress


Update:

still cant undestand, in footer.php

if(!is_user_logged_in()) {
    echo '123';
}

echos 123
but my function does not redirect.. but its still strange and have problem with another plugin because of this.

plugin looks like this:

add_action("wp_footer","bpln_store_ids");
function bpln_store_ids(){
    if(!is_user_logged_in())
        return;
 ?>
 <div id="bpln-notification-ids" style="display:none;">
 <?php echo join(",",bpln_get_all_notification_ids(bp_loggedin_user_id()));?>
 </div>
<?php
}

since check returns true, the actual content will never be displayed

Related posts

1 comment

  1. Please try this for your redirect:

    add_action( 'template_redirect', function(){
    
        // no non-authenticated users allowed
        if( ! is_user_logged_in() )
        {
            wp_redirect( home_url( '/wp-login.php' ), 302 );
            exit();
        }
    });
    

    to allow only logged in users to view your site.

    It’s generally too late to use redirect directly in the header.php file, so it’s better to use an hook that fires before http headers are sent, like the template_redirect hook. It’s also important that template_redirect is not activated on the wp-login.php page.

Comments are closed.