Joel Rosen
Joel Rosen

Reputation: 157

How to block admin area unless username is X (not user role is) in WordPress?

I have a site where I want some users to have the role type of admin but still not be able to access the admin area (don't ask!) This is more of a temporary fix whilst my new site is being built.

I am using this code at the moment which blocks everyone to the admin area unless role type is admin - but how can I block admin unless username is 'mack' for example.

add_action( 'init', 'blockusers_init' );
function blockusers_init() {
    if ( is_admin() && ! current_user_can( 'administrator' ) &&
        ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
      wp_redirect( home_url() );
      exit;
    }
}

Obviously the user still needs to access all other front end pages of the site, just not the admin area.

Upvotes: 1

Views: 130

Answers (2)

Sylwit
Sylwit

Reputation: 1577

If you want a temporary fix without working in your code maybe can you disable user

https://srd.wordpress.org/plugins/disable-users/

Otherwise as @Eduardo say you can do something like this

add_action( 'init', 'blockusers_init' );
function blockusers_init() {
    $current_user = wp_get_current_user();
    if ( is_admin() && ! current_user_can( 'administrator' ) &&
        ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) && $current_user->user_login != 'mack' ) {
      wp_redirect( home_url() );
      exit;
    }
}

Upvotes: 0

Eduardo Escobar
Eduardo Escobar

Reputation: 3389

use wp_get_current_user():

$current_user = wp_get_current_user();
if ($current_user->user_login != 'mack') {
    //It's not mack...
}

Upvotes: 4

Related Questions