This code count comments per day on all pages. I want that will count only on one page for 1 day. So my case: on a page with an ID of 1
, a user can comment with out any limit, but on a page with an ID of 2
, the same user can only comment once per day.
<?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;
}
Limiting comments per day and per user is already built into your current query. The only thing missing is a check for the post ID. Here’s a pretty convenient function/template tag:
/**
* @param int $limit
* @param int $time
* @param int $ids
*/
function is_user_limit_reached( $limit = 5, $time = 1, $ids = array() )
{
global $wpdb;
// Cast to array
! is_array( $limited ) AND $limited = array( $limited );
// Generate SQL clause
$ids = ! empty( $ids )
? sprintf( " and comment_post_ID in (%s)", join( ",", $ids ) )
: "";
// Rows: user_id, comment_date, comment_post_ID
$count = $wpdb->query( $wpdb->prepare(
"select count(*)
from {$wpdb->comments}
where user_id=%d
and comment_date >= date_sub( now(), interval %d day )
%s",
get_current_user_id(),
$time,
$ids
) );
return $count >= $limit;
}
You can use it like this:
if ( is_user_limit_reached(
10, // allowed comments per day
7, // in the last 7 days
array( 1, 35, 97, 1148 ) // array of post IDs which have a limit
) )
{
echo 'Your limit is already reached. Come back tomorrow';
}
else
{
comment_form();
}
You could as well switch the comment box template tag on/off, etc. The sky is your limit.