Preventing administrator to redirect from wp-admin or allow only admin to access wp-admin area

Question

I am restricting non-admin users to access wp-admin using the below code. Also, block wp-login.php as well. For that, I have set up a frontend login page.

function block_backend_access() {

    // WP tracks the current page - global the variable to access it
    global $pagenow;
    // Check if a $_GET['action'] is set, and if so, load it into $action variable
    $action = ( isset( $_GET[ 'action' ] ) ) ? $_GET[ 'action' ] : '';
    // Check if we're on the login page, and ensure the action is not 'logout'
    if ( $pagenow == 'wp-login.php' && ( ! $action || ( $action && ! in_array( $action, login_actions() ) ) ) ) {

        wp_redirect(home_url());
        exit();
    }

    if ( is_admin() && ! current_user_can( 'administrator' ) && ! wp_doing_ajax() ) {
        wp_redirect(home_url());
        exit();
    }
}

add_action( 'init', 'block_backend_access' );

// login_actions
function login_actions() {
    return [
        'logout',
        'lostpassword',
        'rp',
        'resetpass',
    ];
}

The above code is working fine on my mac. It is working on local dev as well as on the production server. But the weird issue is when my client tries to access the dashboard as an admin, they are always getting redirect. Their team tried to access the dashboard from multiple locations. Australia, the Philippines, Europe, etc. none of them work. But it works for me without any single redirection.

.htaccess

# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On

# Force HTTPS redirection
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# End force https redirection

RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# BEGIN Theme

# The directives (lines) between `BEGIN Theme` and `END Theme` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
RewriteCond %{REQUEST_URI} .(pdf|zip|gif|jpg|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(.*)$ dl-file.php?file=$1 [QSA,L]

# END Theme

Question
To investigate the issue, when I removed this action, they can access the dashboard. So I have no idea what is wrong with this code and why I can access it, but my client and team can not.

0
, , , pixelngrain 7 months 0 Answers 98 views 0

Leave an answer