X

How to Ban Users Accounts in WordPress

Snippets by IsItWP

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.

Instructions:

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.

If you liked this code snippet, please consider checking out our other articles on the site like: 20 best WordPress church themes for expanding the flock and how to use Google optimize in WordPress.

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!