Reputation: 97
I just want to sort posts from a standard query based on last comment date. I tried something like this (code below) but I can't get it right. PS: 'dzialy' => $cat
this is custom taxonomy named dzialy
and $cat
is specified id of that category.
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;
}
...and later on...
$args = array( 'post_type' => 'forum', 'dzialy' => $cat, 'posts_per_page' => $ilosc, 'orderby'=>'comment_date', 'order'=>'DESC', );
print_r($loop->query);
...after that…
Array ( [post_type] => forum [dzialy] => 1468 [posts_per_page] => 20 [orderby] => comment_date [order] => DESC )
Upvotes: 0
Views: 702
Reputation: 64496
You can use JOIN
and wpdb class to run your raw sql queries
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
Upvotes: 1
Reputation: 685
try this code,
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
Reference : Ordering Wordpress posts by most recent comment
Hope this helps you
Upvotes: 0