自定义查询根据上次评论日期对帖子进行排序

时间:2014-04-17 14:01:45

标签: php wordpress

我只想根据上次评论日期对标准查询中的帖子进行排序。我试过这样的事情(下面的代码),但我无法做到。 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 [posts_per_page] => 20   [orderby] => comment_date [order] => DESC)

2 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:0)

试试这段代码,

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

参考:Ordering Wordpress posts by most recent comment

希望这有助于你