如何获得每小时、每年和每月的帖子和评论量?

时间:2013-08-03 作者:user1627363

我有以下片段:

function count_user_comments_today( $uid ){
    global $wpdb;
    $today = date(\'Y-m-d\');
    $tomorrow = date(\'Y-m-d\', time() + 86400);
    $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->comments} WHERE user_id = %d  AND comment_date >= %s  AND comment_date < %s ", $uid, $today, $tomorrow  ));
    return $count;
}
但这是每天的评论,也是针对特定用户的评论。我希望它是通用的,为整个网站和每小时,每年和每月。。。。这可能吗?当然还有帖子,不仅仅是评论。

2 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

有关评论:

function count_comments_in_period( $date_from, $date_to ){
    global $wpdb;
    $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_date >= %s  AND comment_date < %s ", $date_from, $date_to));
    return $count;
}
只需在中使用日期yyyy-mm-dd 总体安排

对于职位:

function count_posts_in_period( $date_from, $date_to ){
    global $wpdb;
    $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_date >= %s  AND post_date < %s ", $date_from, $date_to));
    return $count;
}

SO网友:s_ha_dum

我没有时间构建这两个函数,也没有时间对这一个进行太多测试,但我认为这至少很接近:

function funky_comment_query_wpse_108830($year, $month, $hour) {

  if (!empty($year)) {
    $sql[] = "YEAR(comment_date) = {$year}";
  }
  if (!empty($month)) {
    $sql[] = "MONTH(comment_date) = {$month}";
  }
  if (!empty($hour)) {
    $sql[] = "HOUR(comment_date) = {$hour}";
  }
  if (empty($sql)) {
    return;
  }

  global $wpdb;
  $sql = implode(\' AND \',$sql);

  $count = $wpdb->get_var("SELECT count(comment_ID) FROM {$wpdb->comments} WHERE {$sql}");
  return $count;
}
echo funky_comment_query_wpse_108830(\'2013\',\'\',\'\');

结束