add_action('init') not work

my code is

add_action('init', 'user_logged_in');
function user_logged_in(){
    if( is_user_logged_in()  is_page('login')){
    wp_redirect(home_url());
    exit;
    }
}

the page slug and name is "login"

I do not want the logged in member to access the login page.

But this code does not work in functions.php.

Can you tell me what went wrong?

Topic actions init login Wordpress

Category Web


I believe init is too early to determine is_page(). Try a later hook, like template_redirect.

function wpse_344136_user_logged_in(){
    if ( is_user_logged_in() && is_page( 'login' ) ){
        wp_redirect( home_url() );
        exit;
    }
}
add_action( 'template_redirect', 'wpse_344136_user_logged_in' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.