禁止指定用户登录(小黑屋) – wordpress教程

在一些多用户的网站上总会有一些用户不怎么受欢迎,得想个办法禁止这些用户登录,如果您的多用户会员制网站还没有小黑屋功能,那么来看看这一篇wordpress教程吧。

实现方法:

在主题根目录下的functions.php文件的<?php下添加以下代码:
//在资料页面添加选项
function dj_rc_admin_init(){
// 编辑用户资料
add_action( 'edit_user_profile', 'dj_rc_edit_user_profile' );
add_action( 'edit_user_profile_update', 'dj_rc_edit_user_profile_update' );
}
add_action('admin_init', 'dj_rc_admin_init' );
//在个人资料页面添加一个复选框
function dj_rc_edit_user_profile() {
if ( !current_user_can( 'edit_users' ) ) {
return;
}
global $user_id;
// 用户不能禁止自己
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == $user_id ) {
return;
}
?>
<h3>权限设置</h3>
<table class="form-table">
<tr>
<th scope="row">禁止用户登录</th>
<td><label for="dj_rc_ban"><input name="dj_rc_ban" type="checkbox" id="dj_rc_ban"
<?php if (dj_rc_is_user_banned( $user_id )){echo 'checked="checked"';} ?> /> 勾起来,盘Ta,什么玩意儿……</label></td>
</tr>
</table>
<?php
}
//添加一个函数来将这个选项的值保存到数据库中
function dj_rc_edit_user_profile_update() {
if ( !current_user_can( 'edit_users' ) ) {
return;
}
global $user_id;
// 用户不能禁止自己
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == $user_id ) {
return;
}
// 锁定
if( isset( $_POST['dj_rc_ban'] ) && $_POST['dj_rc_ban'] = 'on' ) {
dj_rc_ban_user( $user_id );
} else { // 解锁
dj_rc_unban_user( $user_id );
}
}
//禁止用户
function dj_rc_ban_user( $user_id ) {
$old_status = dj_rc_is_user_banned( $user_id );
// 更新状态
if ( !$old_status ) {
update_user_option( $user_id, 'dj_rc_banned', true, false );
}
}
//解禁用户
function dj_rc_unban_user( $user_id ) {
$old_status = dj_rc_is_user_banned( $user_id );
// 更新状态
if ( $old_status ) {
update_user_option( $user_id, 'dj_rc_banned', false, false );
}
}
//判断用户是否被禁止
function dj_rc_is_user_banned( $user_id ) {
return get_user_option( 'dj_rc_banned', $user_id, false );
}
//阻止已禁止的用户登录
function dj_rc_authenticate_user( $user ) {
if ( is_wp_error( $user ) ) {
return $user;
}
// 如果用户被禁止,则返回错误提示,这里是显示给登录用户看的,错误提示可根据自己的喜好修改。
$banned = get_user_option( 'dj_rc_banned', $user->ID, false );
if ( $banned ) {
return new WP_Error( 'dj_rc_banned', __('您已被关入小黑屋,请联系管理员解封', 'rc') );
}
return $user;
}
//将该函数挂载到 wp_authenticate_user 钩子
add_filter( 'wp_authenticate_user', 'dj_rc_authenticate_user', 1 );
保存即可。

如何使用?

在“所有用户”中找到您需要禁止登录的用户,在其“个人资料”底部有相关选项:
图片[1]-禁止指定用户登录(小黑屋) – wordpress教程-壹念弎仟网络论坛
© 版权声明
THE END
喜欢就支持一下吧
点赞12赞赏 分享
评论 共1条

请登录后发表评论


    Warning: Undefined variable $ip1num in /www/wwwroot/bbs.ctosv.com/show-useragent/ip2c-text.php on line 21

    Warning: Undefined variable $ip2num in /www/wwwroot/bbs.ctosv.com/show-useragent/ip2c-text.php on line 21

    Warning: Undefined variable $ipAddr2 in /www/wwwroot/bbs.ctosv.com/show-useragent/ip2c-text.php on line 87

    Warning: Undefined variable $ipAddr1 in /www/wwwroot/bbs.ctosv.com/show-useragent/ip2c-text.php on line 91