WordPress 限制某些用户登录

  • 酉灿
  • WordPress
  • Jul 23, 2021

在一些情况下,比如某些用户损害了网站的利益,有不方便直接删除账号的,你可能就需要禁止他们登录网站,今天咱们就来介绍下wordpress如何添加禁止用户登录。

将下面代码添加到当前主题函数模板 functions.php中即可。


 
  1. //WordPress 禁止某些用户登录
  2. //在资料页面添加选项
  3. function lxtx_rc_admin_init() {
  4. // 编辑用户资料
  5. add_action( 'edit_user_profile', 'lxtx_rc_edit_user_profile' );
  6. add_action( 'edit_user_profile_update', 'lxtx_rc_edit_user_profile_update' );
  7. }
  8.  
  9. add_action( 'admin_init', 'lxtx_rc_admin_init' );
  10. //在个人资料页面添加一个复选框
  11. function lxtx_rc_edit_user_profile() {
  12. if ( !current_user_can( 'edit_users' ) ) {
  13. return;
  14. }
  15.  
  16. global $user_id;
  17. // 用户不能禁止自己
  18. $current_user = wp_get_current_user();
  19. $current_user_id = $current_user->ID;
  20. if ( $current_user_id == $user_id ) {
  21. return;
  22. }
  23. ?>
  24.  
  25. <h3>权限设置</h3>
  26.  
  27. <table class="form-table">
  28. <tr>
  29. <th scope="row">禁止用户登录</th>
  30. <td><label for="lxtx_rc_ban"><input name="lxtx_rc_ban" type="checkbox" id="lxtx_rc_ban" <?php if (lxtx_rc_is_user_banned( $user_id )){echo 'checked="checked"';} ?> /> 请谨慎操作,选中则禁止!</label></td>
  31. </tr>
  32. </table>
  33. <?php
  34. }
  35.  
  36. //添加一个函数来将这个选项的值保存到数据库中
  37. function lxtx_rc_edit_user_profile_update() {
  38. if ( !current_user_can( 'edit_users' ) ) {
  39. return;
  40. }
  41.  
  42. global $user_id;
  43. // 用户不能禁止自己
  44. $current_user = wp_get_current_user();
  45. $current_user_id = $current_user->ID;
  46. if ( $current_user_id == $user_id ) {
  47. return;
  48. }
  49. // 锁定
  50. if( isset( $_POST['lxtx_rc_ban'] ) && $_POST['lxtx_rc_ban'] = 'on' ) {
  51. lxtx_rc_ban_user( $user_id );
  52. } else { // 解锁
  53. lxtx_rc_unban_user( $user_id );
  54. }
  55. }
  56.  
  57. //禁止用户
  58. function lxtx_rc_ban_user( $user_id ) {
  59. $old_status = lxtx_rc_is_user_banned( $user_id );
  60. // 更新状态
  61. if ( !$old_status ) {
  62. update_user_option( $user_id, 'lxtx_rc_banned', true, false );
  63. }
  64. }
  65.  
  66. //解禁用户
  67. function lxtx_rc_unban_user( $user_id ) {
  68. $old_status = lxtx_rc_is_user_banned( $user_id );
  69. // 更新状态
  70. if ( $old_status ) {
  71. update_user_option( $user_id, 'lxtx_rc_banned', false, false );
  72. }
  73. }
  74.  
  75. //判断用户是否被禁止
  76. function lxtx_rc_is_user_banned( $user_id ) {
  77. return get_user_option( 'lxtx_rc_banned', $user_id, false );
  78. }
  79.  
  80. //阻止已禁止的用户登录
  81. function lxtx_rc_authenticate_user( $user ) {
  82. if ( is_wp_error( $user ) ) {
  83. return $user;
  84. }
  85. // 如果用户被禁止,则返回错误提示
  86. $banned = get_user_option( 'lxtx_rc_banned', $user->ID, false );
  87. if ( $banned ) {
  88. return new WP_Error( 'lxtx_rc_banned', __( '抱歉,该用户被禁止登录!请联系站长解禁。', 'rc' ) );
  89. }
  90. return $user;
  91. }
  92.  
  93. //将该函数挂载到 wp_authenticate_user 钩子
  94. add_filter( 'wp_authenticate_user', 'lxtx_rc_authenticate_user', 1 );

添加完成后,即可在后台“编辑用户”页面里看到增加的“禁止用户登录”选项了,选中后,则会禁止该用户登录。

打赏