Block A WordPress User Programatically

block a wordpress user programatically

Block A WordPress User Programatically

 |   |  0
Programming WordPress

Here, I will describe how to block a WordPress user programatically. It will store a user meta option that will indicated that the user isn’t allowed anymore to login to your website.

We just need to add the filter:

add_filter( 'wp_authenticate_user', 'ins_authenticate_user', 1 );

We created a function to ban a WordPress user. To do so we need to use a WordPress default filter called "wp_authenticate_user". To this filter we’ll hook a function called "ins_authenticate_user()". This function will use the WP_Error class.

/*----------- Block user callback -----------*/
function ins_authenticate_user( $user ) {
  if ( is_wp_error( $user ) ) { return $user; }
 
  // Return error if user account is blocked - if not uploaded and verified the terms
  $blocked = get_user_option( 'afl_blocked', $user->ID, false );
  if ( $blocked ) {
    return new WP_Error( 'afl_blocked', t('ERROR: This user account is disabled.') );
  }
  return $user;
}
/*----------- Block user callback -----------*/

And we finally hooked a function to the "wp_authenticate_user" filter using the WP_Error WordPress default class. Now add below code to block a user in your function. You must pass the user id to update_user_option() and the user will be blocked.

$uid = 10; // The user id to block
update_user_option( $uid, 'afl_blocked', true );

0 Claps

Show your love in the form of Claps and Comments...

Comments...

No comments found. Leave your reply here.