I want to limit the access to a wordpress app only to registered users.
I've putted this inside the function file, but I'm able to see the home also if I'm not logged in. How I fix this?
if( is_home() || is_page() || is_single() && !is_user_logged_in() ){
wp_safe_redirect( wp_login_url() );
}
I want to limit the access to a wordpress app only to registered users.
I've putted this inside the function file, but I'm able to see the home also if I'm not logged in. How I fix this?
if( is_home() || is_page() || is_single() && !is_user_logged_in() ){
wp_safe_redirect( wp_login_url() );
}
Share
Improve this question
asked Feb 11, 2020 at 19:35
sialfasialfa
32910 silver badges29 bronze badges
2 Answers
Reset to default 0This works only for blog pages, pages, and single posts. You need to disable redirection on the login page. Here you can find how to detect the login page. Check if wp-login is current page
So to redirect globally as you want use:
if(!is_user_logged_in() && !is_wplogin() ) wp_safe_redirect( wp_login_url() );
Function is_wplogin() is from here: https://wordpress.stackexchange/a/237285/181863
I also prefer to do redirection after init:
function is_wplogin(){
$ABSPATH_MY = str_replace(array('\\','/'), DIRECTORY_SEPARATOR, ABSPATH);
return ((in_array($ABSPATH_MY.'wp-login.php', get_included_files()) || in_array($ABSPATH_MY.'wp-register.php', get_included_files()) ) || (isset($_GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php') || $_SERVER['PHP_SELF']== '/wp-login.php');
}
add_action('init', function () {
if (!is_user_logged_in() && !is_wplogin()) {
wp_redirect(wp_login_url());
die();
}
});
is_home()
is for the page that shows the recent blog posts.
If you have set a static page as front page, then that check doesn't return true
there. Add a check for is_front_page()
to cover that case.