按最新评论订购Wordpress帖子

Jam*_*man 5 php mysql wordpress

我想通过最新评论订购Wordpress帖子.据我所知,使用WP_Query对象是不可能的,并且需要一个我可以轻松编写的自定义$ wpdb查询.但是,我不知道如何设置循环以运行此对象.

有人可以帮忙吗?

hao*_*hao 7

分配

select wp_posts.*, max(comment_date) as max_comment_date
from $wpdb->posts wp_posts
right join $wpdb->comments
on id = comment_post_id
group by ID
order by max_comment_date desc
limit 10
Run Code Online (Sandbox Code Playgroud)

一些变量$ query.您可以使用10或查询本身.(我不是SQL优化忍者.)然后你的代码看起来像

<?php
     $results = $wpdb->get_results($query) or die('!');
     foreach ($results as $result):
?>
[insert template here]
<?php endforeach ?>
Run Code Online (Sandbox Code Playgroud)

食典委更深入地介绍了这种模式.


小智 3

好了朋友们,

这里有很多很好的答案,但显然没有人花时间来测试它们。

郝连获得了第一个最佳原始答案的荣誉,但不幸的是他的代码不显示没有评论的帖子。

Captain Keytar 的方向是正确的,但他的代码会将每个帖子和附件显示为单独的结果。

这是 Captain Keytar 的修改版本,但它将结果限制为已发布的“帖子”类型(以避免收到草稿!!)

    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
Run Code Online (Sandbox Code Playgroud)