Prevent access for users which are not logged in WordPress

22.Sep.2014

We all have our small and big WordPress projects. Sometimes we want to allow our clients to see what has been done so far, but we don’t want anybody else to see it. The easiest way to define this is: prevent access for users which are not logged in WordPress administration.

Sure – you can use .htaccess for content protection, but there is a much more simple way.

Since our clients already have access to the website administration, we can just allow them to log in, and then view the website as it currently is. This way we will prevent all the users which we don’t want to see our website, and those are the ones with no access data to administration.

Just copy and paste following lines to functions.php file, and you will have your redirect set in no time.

1
2
3
4
5
6
7
8
function prevent_unauthorized_access() {
    if(!is_user_logged_in()) {
        header('location: ' . wp_login_url());
        die;
    }
}
 
add_action('wp_head', 'prevent_unauthorized_access');