首页 > 解决方案 > 按时间段排列的评论最多的帖子(在 Wordpress 中)

问题描述

我有这段代码,效果很好。

 <?php 
      $result = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 25"); // NUMBER OF POSTS
         foreach ($result as $topten) {
             $postid = $topten->ID;
             $title = $topten->post_title;
             $commentcount = $topten->comment_count;
             if ($commentcount != 0) {
      ?>
        <a href="<?php echo get_permalink($postid); ?>"><span class="tags"> <?php echo $title ?></span></a>
   
   <?php } } ?>

现在它按评论计数(所有时间)显示(排序)最受欢迎的帖子。

我知道 WordPress 理解命令“句点”:

   period=1hourago

基本上,我试图让上面的代码与这个时期一起工作,这样我就可以定义:

24小时前

或者

12小时前

等等...

我知道我需要以某种方式将其集成到代码中:

 'date_query' => [
        [
           
        ]
    ],

但我似乎无法找到一种将所有内容放在一起的方法。

需要帮忙。

标签: phpmysqldatabasewordpress

解决方案


您可以更新您的 SQL 查询以使用 JOIN 语句在某个时间范围内搜索评论表中的项目,并重构您的代码以将评论计数检查移动到查询中:

 // Target timeframe
$time   = time();
$range  = strtotime('-6 hours', $time);

// Convert to GMT to match DB
$start  =  date('Y-m-d H:i:s', $time);
$end    =  date('Y-m-d H:i:s', $date);

// Update with comment table search and post comment count
$result = $wpdb->get_results(
    "SELECT p.comment_count, p.ID, p.post_title 
    FROM $wpdb->posts AS p
        JOIN $wpdb->comments AS c
            ON ( p.ID = c.comment_post_ID )
    WHERE c.comment_date < '$start' AND c.comment_date > '$end'
    AND p.comment_count > 0
    ORDER BY p.comment_count DESC LIMIT 0 , 25"
);

foreach ($result as $topten) {
    $link = get_permalink( $topten->ID );
    $title = $topten->post_title;
    printf ( "<a href='%s'><span class='tags'>'%s</span></a>", $link,  $title );
}

您还可以像这样搜索日期:

    $start  = date('Y-m-d H:i:s', strtotime('2007-11-21'));
    $end    = date('Y-m-d H:i:s', strtotime('2007-11-21 -24 hours'));

推荐阅读