您需要使用posts\\u groupby过滤器两次。它们可能看起来像这样:
function add_my_groupby($groupby, &$query) {
global $wpdb;
$groupby .= "$wpdb->posts.ID";
return $groupby;
}
function add_my_having($groupby, &$query) {
$groupby .= " HAVING COUNT(*) >= 5";
return $groupby;
}
然后,您需要在模板中执行类似操作:
add_filter(\'posts_groupby\', \'add_my_groupby\', 10, 2);
add_filter(\'posts_groupby\', \'add_my_having\', 1000000, 2);
query_posts( array(/* your stuff...*/) );
remove_filter(\'posts_groupby\', \'add_my_groupby\', 10);
remove_filter(\'posts_groupby\', \'add_my_having\', 1000000);
(请注意,为第二个过滤器的优先级传递了非常大的数字。这是为了解决WP API中缺少具有过滤器的POST\\u的问题。)
或者,不要使用query\\u posts()垃圾,直接查询数据库,例如:
$wpdb->get_results("
SELECT posts.*
FROM $wpdb->posts as posts
JOIN $wpdb->postmeta as postmeta
ON postmeta.post_id = posts.ID
AND postmeta.meta_key = \'whatever\'
GROUP BY posts.ID
HAVING COUNT(*) >= 5
ORDER BY posts.post_date DESC
LIMIT 5
");
更新:正如Jan所指出的,应该是这样的:
HAVING COUNT(DISTINCT postmeta.post_id) >= 5
如果有其他连接。