Home >Backend Development >PHP Tutorial >WordPress restricts non-admin users to comment only once after an article, wordpress_PHP tutorial
Some netizens have previously asked whether there is a way in WordPress to only allow users to comment on each article. once?
Let’s not say whether this requirement is useful or not. After all, WordPress is for people with various needs. This function is relatively simple to implement. You only need to search all the comments on the current article to see if the same user name or email address has already posted a comment. If so, jump to the error page. .
To implement the code, just put it in the functions.php of the current theme (the IP judgment is also added here, which is safer):
// 获取评论用户的ip,参考wp-includes/comment.php function ludou_getIP() { $ip = $_SERVER['REMOTE_ADDR']; $ip = preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip ); return $ip; } function ludou_only_one_comment( $commentdata ) { global $wpdb; $currentUser = wp_get_current_user(); // 不限制管理员发表评论 if(empty($currentUser->roles) || !in_array('administrator', $currentUser->roles)) { $bool = $wpdb->get_var("SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = ".$commentdata['comment_post_ID']." AND (comment_author = '".$commentdata['comment_author']."' OR comment_author_email = '".$commentdata['comment_author_email']."' OR comment_author_IP = '".ludou_getIP()."') LIMIT 0, 1;"); if($bool) wp_die('本站每篇文章只允许评论一次。<a href="'.get_permalink($commentdata['comment_post_ID']).'">点此返回</a>'); } return $commentdata; } add_action( 'preprocess_comment' , 'ludou_only_one_comment', 20);
There is no limit on the number of comments an administrator can make, so let’s take a look at how to determine whether a user is an administrator:
Determine whether the user with the specified ID is an administrator
This requirement is very simple to implement. It can be done with just a few lines of code. Let me share it:
function ludou_is_administrator($user_id) { $user = get_userdata($user_id); if(!empty($user->roles) && in_array('administrator', $user->roles)) return 1; // 是管理员 else return 0; // 非管理员 }
Determine whether the currently logged in user is an administrator
If you want to determine whether the currently logged in user is an administrator, you can use the following function:
function ludou_is_administrator() { // wp_get_current_user函数仅限在主题的functions.php中使用 $currentUser = wp_get_current_user(); if(!empty($currentUser->roles) && in_array('administrator', $currentUser->roles)) return 1; // 是管理员 else return 0; // 非管理员 }