Answers:
下面的答案被简化,并且可以扩展以检查是否任何职位有输出列表前3个匹配的标签。使用一个查询并假设您至少有一个带有3个匹配标签的帖子:
//List of tag slugs
$tags = array('foo', 'bar', 'chocolate', 'mango', 'hammock', 'leaf');
$args = array(
'tag_slug__in' => $tags
//Add other arguments here
);
// This query contains posts with at least one matching tag
$tagged_posts = new WP_Query($args);
echo '<ul>';
while ( $tagged_posts->have_posts() ) : $tagged_posts->the_post();
// Check each single post for up to 3 matching tags and output <li>
$tag_count = 0;
$tag_min_match = 3;
foreach ( $tags as $tag ) {
if ( has_tag( $tag ) && $tag_count < $tag_min_match ) {
$tag_count ++;
}
}
if ($tag_count == $tag_min_match) {
//Echo list style here
echo '<li><a href="'. get_permalink() .'" title="'. get_the_title() .'">'. get_the_title() .'</a></li>';
}
endwhile;
wp_reset_query();
echo '</ul>';
编辑:调整变量$tag_min_match
将设置匹配数。
这是一种实现方法:
给定一组5个标签,{a, b, c, d, e}
:
1)在PHP中,生成所有可能的包含3个元素的子集,而无需重复:
{a, b, c}
{a, b, d}
{a, b, e}
{a, c, d}
{a, c, e}
{b, c, d}
{b, c, e}
{c, d, e}
2)将这些子集转换为大规模分类法查询:
$q = new WP_Query( array(
'tax_query' => array(
'relation' => 'OR',
array(
'terms' => array( 'a', 'b', 'c' ),
'field' => 'slug',
'operator' => 'AND'
),
array(
'terms' => array( 'a', 'b', 'd' ),
'field' => 'slug',
'operator' => 'AND'
),
...
)
) );
我使用的是sprclldr的方法。至于while循环,这是我改用的:
$relatedPosts = $tagged_posts->posts;
$indexForSort = array();
for ($i = count($relatedPosts) - 1; $i >= 0; $i--) {
$relatedPostTags = get_tags($relatedPosts[$i]->ID);
//get the ids of each related post
$relatedPostTags = $this->my_array_column($relatedPostTags, 'term_id');
$relatedPostTagsInPostTag = array_intersect($tags, $relatedPostTags);
$indexForSort[$i] = count($relatedPostTagsInPostTag);
}
//sort by popularity, using indexForSort
array_multisort($indexForSort, $relatedPosts, SORT_DESC);
然后,我走在最上面的帖子:
$a_relatedPosts = array_slice($relatedPosts, 0, $this->numberRelatedPosts);
my_array_column
与PHP 5,5的array_column类似的功能:
protected function my_array_column($array, $column) {
if (is_array($array) && !empty($array)) {
foreach ($array as &$value) {
//it also get the object's attribute, not only array's values
$value = is_object($value) ? $value->$column : $value[$column];
}
return $array;
}
else
return array();
}
它没有回答最初的问题(但是它解决了我的根本问题),例如:如果没有带有3个通用标签的相关帖子,那么所有这些都将给出相同的帖子。