php - Restrict wordpress access to logged users only

I want to limit the access to a wordpress app only to registered users.I've putted this inside the function file, b

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
Add a comment  | 

2 Answers 2

Reset to default 0

This 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744757816a4591985.html

相关推荐

  • php - Restrict wordpress access to logged users only

    I want to limit the access to a wordpress app only to registered users.I've putted this inside the function file, b

    9小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信