Are you looking for a way to allow the admin to band WordPress user accounts? While there’s probably a plugin for this, we have created a quick code snippet that you can use to ban users accounts in WordPress.

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

// 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['ban_user'] );
}
 
// 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;
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
100 %
Angry
Angry
0 %
Surprise
Surprise
0 %