There is no argument to restrict a comment query directly to a given date. You have to filter the query later:
/**
* Get the number of comments for a post today.
*
* @param int $post_id
* @return int
*/
function t5_count_comments_today( $post_id = NULL )
{
if ( NULL === $post_id )
$post_id = get_the_ID();
add_filter( 'comments_clauses', 't5_comments_today_sql' );
// get_comments() returns a string even with 'count' set to TRUE.
return (int) get_comments(
array (
'post_id' => $post_id,
'count' => TRUE
)
);
}
/**
* Add date specific WHERE clause to comment query.
*
* Deactivates itself to avoid collisions with regular comment queries.
*
* @wp-hook comments_clauses
* @param array $clauses
* @return array
*/
function t5_comments_today_sql( $clauses )
{
// avoid collisions
remove_filter( current_filter(), __FUNCTION__ );
global $wpdb;
$clauses['where'] .= $wpdb->prepare( ' AND comment_date >= %s', date( 'Y-m-d 00:00:00' ) );
return $clauses;
}
Simple usage
echo t5_count_comments_today();
Or, if you don’t want to show zero comments:
$comments_today = t5_count_comments_today();
if ( 0 < $comments_today )
echo $comments_today;
Extended use case
This adds the number to the text of comments_popup_link()
.
is_admin() || add_filter( 'comments_number', 't5_comment_number_today', 10, 2 );
/**
* Add formatted number to total comments number.
*
* @wp-hook comments_number
* @param string $output
* @param int $number Might be a string, so we cast it to int.
* @return string
*/
function t5_comment_number_today( $output, $number )
{
// no comments at all, no need to count today's comments
if ( 0 === (int) $number )
return $output;
$count = t5_count_comments_today();
$add = 'no comments today'; // default text
if ( 1 === $count )
$add = 'one comment today';
if ( 1 < $count )
$add = "$count comments today";
return "$output ($add)";
}
Side note: Always use get_comments()
or the class WP_Comment_Query
for which get_comments()
is a wrapper, because that result will be cached, so you will never have to fetch the same value for an identical argument list twice.
Avoid non-API calls with raw SQL in these cases.