没有参数可以将注释查询直接限制到给定日期。以后必须过滤查询:
/**
* 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;
}
简单用法
echo t5_count_comments_today();
或者,如果您不想显示零评论:
$comments_today = t5_count_comments_today();
if ( 0 < $comments_today )
echo $comments_today;
扩展用例将数字添加到
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)";
}
旁注:始终使用
get_comments()
或班级
WP_Comment_Query
为此
get_comments()
是一个包装器,因为结果将被缓存,所以您永远不必为相同的参数列表两次获取相同的值
在这些情况下,请避免使用原始SQL进行非API调用。