自定义查询,根据最后评论日期对帖子进行排序


Custom query which sorts posts based on last comment date

我只想根据最后一条评论日期对标准查询中的帖子进行排序。我试过这样的东西(下面的代码),但我做不好。PS:'dzialy' => $cat这是名为dzialy的自定义分类法,$cat是该类别的指定id。

function forum_commentsjoin($join) {
 global $wp_query, $wpdb;
 if ($wp_query->query_vars['post_type']=='forum' && isset($wp_query->query_vars['dzialy'])) {
  $join .= "LEFT JOIN $wpdb->comments ON $wpdb->comments.comment_post_ID=$wpdb->posts.ID"; 
 } 
 return $join; 
}

稍后…

$args = array( 'post_type' => 'forum', 'dzialy' => $cat, 'posts_per_page' => $ilosc, 'orderby'=>'comment_date', 'order'=>'DESC', );
print_r($loop->query); 

之后…

数组([post_type]=>论坛[dzialy]=>1468[post_per_page]=>20[orderby]=>comment_date[order]=>DESC)

您可以使用JOINwpdb class来运行原始sql查询

SELECT DISTINCT p.* 
FROM 
`wp_posts` p
LEFT JOIN  `wp_comments` c ON(p.`ID`=c.`comment_post_ID`)
WHERE p.`post_status`='publish'
AND p.`post_type`='forum'
ORDER BY c.`comment_date` DESC

试试这个代码,

select wp_posts.*,
    coalesce(
        (
            select max(comment_date)
            from $wpdb->comments wpc
            where wpc.comment_post_id = wp_posts.id
        ),
        wp_posts.post_date
    ) as mcomment_date
    from $wpdb->posts wp_posts
    where post_type = 'post'
    and post_status = 'publish' 
    order by mcomment_date desc
    limit 10

参考:按最新评论排序Wordpress帖子

希望这能帮助您