如何禁止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 后,后台“编辑用户”时,您就会发现多了一个“禁止用户评论”的选项如下:
如何禁止WordPress某些用户评论? (https://www.wp-admin.cn/) WordPress开发教程 第1张
我们发现上面只是实现了禁言的方法,下面就来把禁言的功能真正使用起来(登录回复可见短代码一直没用过,这次就来用上试试效果~ )。

//阻止已禁止的用户评论

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某些用户评论? (https://www.wp-admin.cn/) WordPress开发教程 第2张

相关推荐

发表回复

房先生
我们将24小时内回复。
2024-07-16 22:50:32
您好,有任何疑问请与我们联系!
您的工单我们已经收到,我们将会尽快跟您联系!
[QQ客服]
2781198
加我微信
[电话联系]
13585372227
[电子邮件]
chaoneo@163.com
取消

选择聊天工具: