問題描述
有一組標籤,其中至少有 3 個這些標籤的帖子應該匹配。
說有 {foo,bar,chocolate,mango,hammock,leaf} 的標籤
我想找到所有這些標籤中至少有 3 個的帖子。
例如,標籤 {foo,mango,vannilla,nuts,leaf} 的帖子將匹配它,因為它具有 {foo,mango,leaf},因此至少需要 3 個標籤。所以它將在匹配的帖子的列表中。
有沒有一個簡單的方法來做到這一點,沒有透過所有的帖子做多個迴圈?
最佳解決方案
下面的答案是簡化的,可以擴充套件,以檢查在輸出列表之前是否有任何帖子有 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="http://'.%20get_permalink()%20.'" title="'. get_the_title() .'">'. get_the_title() .'</a></li>';
}
endwhile;
wp_reset_query();
echo '</ul>';
編輯:調整變數 $tag_min_match 將設定匹配次數。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。