这个答案确保了相关帖子是按照匹配的标签数量排序的。
例如,如果一篇文章有3个标签,而另一篇文章有完全相同的3个标签,那么它应该显示在列表的顶部。二级排序应按发布日期进行,以便于更新内容。
/**
* Select content with common tags.
* Sort so content with multiple matching tags are at the top.
* Secondary sort on most recent content first.
*
* @param $post_id
* @param int $limit
* @return array
*/
function related_posts($post_id, $limit = 5) {
global $wpdb;
$query = "SELECT TOP %d x.object_id as ID
FROM (
SELECT TOP 10 tr1.object_id, COUNT(tr1.term_taxonomy_id) AS common_tag_count
FROM {$wpdb->term_relationships} AS tr1
INNER JOIN {$wpdb->term_relationships} AS tr2 ON tr1.term_taxonomy_id = tr2.term_taxonomy_id
WHERE tr2.object_id = %d
GROUP BY tr1.object_id
HAVING tr1.object_id != %d
ORDER BY COUNT(tr1.term_taxonomy_id) DESC
) x
INNER JOIN {$wpdb->posts} p ON p.ID = x.object_id
ORDER BY common_tag_count DESC, p.post_date DESC;";
$query = $wpdb->prepare($query, $limit, $post_id, $post_id);
$ids = $wpdb->get_col($query);
$posts = [];
foreach($ids as $id) {
$posts[] = get_post($id);
}
return $posts;
}
这里的内部查询是选择标签最匹配的内容,然后外部查询只是用于按发布日期进行二次排序。
注意:此查询是为SQL Server编写的,因此某些语法可能需要更新(例如,TOP vs LIMIT)。