X

Ban users accounts in WordPress

Sometimes you only need a simple solution rather than a giant plugin with loads of extra features. This simple snippet allows the admin to ban WordPress user accounts. It will add a simple checkbox to user pages that, when checked, will block users from logging in.

// display checkbox to admin
add_action( 'edit_user_profile', 'ban_user_profile_fields' );
function ban_user_profile_fields( $user ) {
 global $current_user;
 if ( current_user_can( 'edit_user' ) && $user->ID != $current_user->ID ){
  $status = get_the_author_meta( 'ban_user', $user->ID  );
  ?>
  <h3><?php _e("Account Status", "blank"); ?></h3>
  <table class="form-table">

  <tr>
       <th>Ban User</th>
       <td><label for="ban_user"><input type="checkbox" name="ban_user" id="ban_user" value="1" <?php if($status == 1){ echo ' checked'; } ?> /></label>
       <span class="description"><?php _e("Check this option to ban this users account."); ?></span>
       </td>
  </tr>

  </table>
  <?php
 }
}

// Save profile update
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ){
      if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
      update_usermeta( $user_id, 'ban_user', $_POST&#91;'ban_user'&#93; );
}

// Check if user is banned
add_filter( 'wp_authenticate_user', 'login_ban_status', 1 );
function login_ban_status($user) {

        if ( is_wp_error( $user ) ) { return $user; }
        $status = get_user_meta( $user->ID, 'ban_user', 'true' );

        if($status == 1){
          return new WP_Error( 'banned', __('<strong>ERROR</strong>: This user account has been banned.', 'banned') );
        }

        return $user;
}

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!