简体   繁体   中英

Wordpress check if user is logged in works wrong

单击此处查看架构!

I'm making an advertisement service, I'm using wordpress template. It works fine, but from a week I realise that I've a problem, I don't know when I destroy something.

When I'll post new ad the page is checking if am I logged in.

if ( !is_user_logged_in() ) {   

    $login = $redux_demo['login'];
    wp_redirect( $login ); exit;
} else {
}

And mostly it redirect me into Login page (I'm logged in). On the Login page it checks:

if ( is_user_logged_in() ) {
    global $redux_demo;
    $profile = $redux_demo['profile'];
    wp_redirect( $profile ); exit;
}

And it is redirecting me into Profile page! So in the first time it return that I'm not logged in, but on the second page it return that I'm logged in. Sometimes it works. For example when I login and wait a few minutes it works correctly, but when I sign out and login there's the same problem. Do you have some ideas how to fix it?

The best practice for redirecting is to use the WordPress action event hook called template_redirect . This event ensures that you are:

  • Checking for the user's login state after that information is available (ie and not too early in the load process)
  • WordPress is ready to accept a redirect

In your use case, you would want to do the following:

add_action('template_redirect', 'redirect_to_login_page_if_not_logged_in');
/**
 * Redirect to the login page if the user is not logged in.
 *
 * @since 1.0.0
 *
 * @return void
 */
function redirect_to_login_page_if_not_logged_in() {
    if ( is_user_logged_in() ) {
        return;
    }

    global $redux_demo;

    if ( isset( $redux_demo['login'] ) ) {
        wp_redirect( esc_url( $redux_demo['login'] ) );
        exit();
    }

    // Redirect to the built-in WordPress login page
    auth_redirect();
}

If the user is logged in, just bail out (with the return ). Else, check if the 'login' key is set in your global variable. If yes, redirect to that page. Else, redirect to the built-in WordPress login page using auth_redirect() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM