最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Restrict wordpress access to logged users only

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论