我想获取包含最新评论的帖子列表。然而,我不想简单地得到最新的评论和重复的帖子,但我想对帖子进行分组(根据它们的ID)。我尝试了以下方法(ff这很重要:代码位于widget类的widget()方法中):
function distinct() {
return "DISTINCT";
}
add_filter(\'posts_distinct\', \'distinct\');
$args = array(
\'number\' => 8
);
$query = new WP_Comment_Query;
$comments = $query->query($args);
posts\\u distinct过滤器似乎是实现这一点的正确方法,但它没有被调用,也不起作用。使用posts\\u groupby的不同方法也不起作用:
add_filter(\'posts_groupby\', \'groupby\' );
function groupby($groupby) {
global $wpdb;
$groupby = "{$wpdb->posts}.ID";
return $groupby;
}
如何进行WP\\u Comment\\u查询以返回8篇杰出的帖子?
我知道我可以简单地使用一个原始的SQL查询,但在一个小时毫无结果的谷歌搜索之后,我真的想知道,如何用WP的方式解决这个问题。
SO网友:Jonathan Gruber
好的,我现在明白了,get\\u comments()只适用于。。。好的评论。下面的内容不是很优雅,但至少可以使用。
$i = 0;
while (count($comments) < $number) {
$comment = get_comments(
apply_filters(
\'widget_comments_args\', array(
\'number\' => 1,
\'status\' => \'approve\',
\'post_status\' => \'publish\',
\'offset\' => $i
)
)
);
if (!isset($comment[0]))
break;
$comment = $comment[0]; // unwrap
$comments[$comment->comment_post_ID] = $comment;
$i++;
}
// Sort by date
// @ to avoid this bug: https://bugs.php.net/bug.php?id=50688
@usort($comments, function ($a, $b) {
return get_the_date(\'U\', $a->comment_post_ID) < get_the_date(\'U\', $b->comment_post_ID);
});
SO网友:lucian
你想要的事情可以做得容易一点。
运行WP_comments_Query
在后台获取带有评论日期的帖子ID数组。然后在法线中使用该数组WP_Query
. 如果您也需要注释,那么可以使用get_comments
作用下面是一个示例:
// For performance, limit the number of queried comments,
// but make it be something big enough to account for "duplicate" posts.
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( array( \'number\' => \'100\' ) );
if ( $comments ) {
foreach ( $comments as $comment ) {
// You\'ll want to convert the dates from string to integer so you can sort them out later
$comment_utf = strtotime($comment->comment_date);
// Build an array of post IDs with the date of the last published comment
$latest_comments[$comment->comment_post_ID] = $comment_utf;
}}
// Sort the array by date
arsort($latest_comments); foreach ($latest_comments as $key => $value) { $posts_ordered[] = $key; }
// The nice thing is that WP_Query will remove duplicates by default
$args = array ( \'posts_per_page\' => \'10\', \'post__in\' => $posts_ordered, \'orderby\' => \'post__in\');
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Do your stuff (add the template or whatever)
// If you want to add the comment itself, use this:
$comments = get_comments(array(\'number\' => \'1\', \'post_id\' => $post->ID));
foreach($comments as $comment) :
echo $comment->comment_content;
endforeach;
// That\'s about it
}}
wp_reset_postdata();