我如何限制每个注册用户每天的评论数量?

时间:2012-08-03 作者:Chad

我在WPSE上找到以下代码:

global $current_user, $post;
$args = array( \'user_id\' => $current_user->ID, \'post_id\' => $post->ID );
$usercomment = get_comments( $args );
if ( 1 <= count( $usercomment ) ) {
    echo \'disabled\';
} else {
    comment_form();
}
注意:这似乎限制了每个用户每篇文章的评论数量

我想限制每个注册用户每天的评论数。

我希望能够更改代码中每天允许的评论数量。

如果有人能帮我找到正确的代码,我将不胜感激。另外,我应该在注释中把这段代码放在哪里。php文件?

非常感谢。

2 个回复
SO网友:Bainternet

您可以按当前用户拉取所有注释并循环查看它们,以查看今天的位置,或者您可以创建自定义sql查询,以仅选择过去24小时的注释计数,如下所示:

global $wpdb,$current_user;
$sql = $wpdb->prepare("
    SELECT count(*)
    FROM wp_comments 
    WHERE comment_author = \'%s\'
    AND comment_date >= DATE_SUB(NOW(),INTERVAL 1 DAY);"
    ,$current_user);
$count = $wpdb->get_results($sql);

SO网友:amit

这是工作版本,我引用了@Bainternet的技术来完成它。只需更换<?php comment_form(); ?> 使用此代码

<?php 
    global $wpdb,$current_user;
    $limit = 5; //this is limit per day per user
    $comment_count = $wpdb->get_var( $wpdb->prepare("
        SELECT count(*)
        FROM wp_comments 
        WHERE comment_author = \'%s\'
        AND comment_date >= DATE_SUB(NOW(),INTERVAL 1 DAY);"
        ,$current_user->user_login) );

    if($comment_count < $limit) {
        comment_form();
    }   
    else {
        echo \'exceeded comments limit - \'.$limit;
    }
?>
在Wordpress 3.4.1上测试,在上安装了二十个主题

注-

  • 只需对当天评论超过5条的用户隐藏评论表单Regardless of comment statusDiscussion Settings

结束