使用 WordPress 已经好几年了,但是我们发现带有会员注册的 wordpress 站点居然都没有禁言功能,如果我们网站在某些时候,个别会员用户的评论严重违反站点规定,那么我们就需对该会员用户进行禁言处理了以示惩罚。于是想折腾折腾看看有什么办法,于是上网搜索相关教程但是基本都是关于 WordPress 文章禁止评论的... 所以只能自己动手测试操作了,具体代码如下:
/**
* WordPress 禁止某些用户评论
*/
//在资料页面添加选项
function lxtx_usercmt_admin_init(){ // 编辑用户资料
add_action( 'edit_user_profile', 'lxtx_usercmt_edit_user_profile' );
add_action( 'edit_user_profile_update', 'lxtx_usercmt_user_profile_update' );
}
add_action('admin_init', 'lxtx_usercmt_admin_init' );//在个人资料页面添加一个复选框
function lxtx_usercmt_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="lxtx_usercmt_ban"><input name="lxtx_usercmt_ban" type="checkbox" id="lxtx_usercmt_ban"
<?php if (lxtx_usercmt_is_user_banned( $user_id )){echo 'checked="checked"';} ?> /> 请谨慎操作,选中则禁止!</label></td>
</tr>
</table>
<?php}//添加一个函数来将这个选项的值保存到数据库中function lxtx_usercmt_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['lxtx_usercmt_ban'] ) && $_POST['lxtx_usercmt_ban'] = 'on' ) {
lxtx_usercmt_ban_user( $user_id );
} else { // 解锁
lxtx_usercmt_unban_user( $user_id );
} }//禁止用户function lxtx_usercmt_ban_user( $user_id ) {
$old_status = lxtx_usercmt_is_user_banned( $user_id );
// 更新状态if ( !$old_status ) {
update_user_option( $user_id, 'lxtx_usercmt_banned', true, false );
}}//解禁用户function lxtx_usercmt_unban_user( $user_id ) {
$old_status = lxtx_usercmt_is_user_banned( $user_id );
// 更新状态if ( $old_status ) {
update_user_option( $user_id, 'lxtx_usercmt_banned', false, false );
}}//判断用户是否被禁止function lxtx_usercmt_is_user_banned( $user_id ) {
return get_user_option( 'lxtx_usercmt_banned', $user_id, false );
}
把上面代码加入 functions.php 后,后台“编辑用户”时,您就会发现多了一个“禁止用户评论”的选项如下:

我们发现上面只是实现了禁言的方法,下面就来把禁言的功能真正使用起来(登录回复可见短代码一直没用过,这次就来用上试试效果~ )。
//阻止已禁止的用户评论function lxtx_usercmt_authenticate_user( $commentdata ) {
if( lxtx_usercmt_is_user_banned( $commentdata['user_ID'] ) ){
err(__('由于严重违反龙笑天下相关规定,该账号已被禁言'));
}else{
return $commentdata;
}}if( is_user_logged_in() ){
add_filter( 'preprocess_comment' , 'lxtx_usercmt_authenticate_user' );
}具体的禁言效果如下图:

是不是简单实用,如果感觉不错您就来照葫芦画瓢做一个吧!
专业提供WordPress主题安装、深度汉化、加速优化等各类网站建设服务,详询在线客服!
