I have developed a WordPress Website. It's on the live server but in development mode.I want if someone to visit my website. It should ask for password or access token to before loading site.

Is there a way to achieve this functionality.

Note: I have put my code in the answer that's working. Please review it. Is this the good way or there is any better way to do this.



I have put the following code in index.php file. It's working fine as I was looking.

define('WP_USERNAME', 'PassW0rd$2017');

$error_msg = '';
$status = session_status();

if (PHP_SESSION_DISABLED === $status) {
    // That's why you cannot rely on sessions!
    // return;
if (PHP_SESSION_NONE === $status) {
if (isset($_SESSION['user_name']) && $_SESSION['user_name'] != '' && $_SESSION['user_name'] == WP_USERNAME) {
    // -------------
} else {

    if (isset($_POST['user_name']) && $_POST['user_name'] != '') {

        if ($_POST['user_name'] == WP_USERNAME) {

            $_SESSION['user_name'] = $_POST['user_name'];
            echo '<script>location.reload();</script>';

        } else {
            // $_SESSION[ 'user_name' ] = $_POST['user_name'];
            $error_msg = 'Invalid access token, Please try again.';
            // echo '<script>location.reload();</script>';


    echo '<div style="width: 350px;margin: 200px auto;padding: 10px;">';

    if ($error_msg) {
        echo '<p style="color:#940d0d">' . $error_msg . '</p>';

    echo '<form method="POST" action="">';
    echo '<label>Please Access token before visiting this site.</label><br/>';
    echo '<input type="text" name="user_name" style="padding: 5px;width: 100%;margin-top: 10px;"><br/>';
    echo '<input type="submit" value="Submit to Access" style="padding: 8px 12px;margin-top: 10px;background: #0dc176;border: 0;color: #fff;cursor: pointer;font-size: 18px;">';
    echo '</form></div>';



You can password protect the root (WordPress root) directory on your webserver using "Basic Authentication". E.g. if you have Apache with Cpanel.

Alternatively, with WordPress itself, you can use auth_redirect. If the user is not logged in, they are redirected to the login page, after log-in they are redirected back to the page they requested.

Simply add this to functions.php or better still make it a plugin which you can activate/deactivate:

if ( ! is_user_logged_in() && strpos($_SERVER['REQUEST_URI'],'wp-login.php') === false) {

The above assumes login is standard (wp-login.php) and ensures auth_redirect is not executed on login page itself (otherwise you will have an infinite redirect loop).

  • actually requirement is just put site behind the password. if someone tries to visit the site, it should ask password. – Gufran Hasan Mar 5 '18 at 3:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.