要在WordPress中隨機(jī)調(diào)用當(dāng)前文章同分類下的相同標(biāo)簽的10篇文章,你可以使用以下代碼。這段代碼將會(huì)獲取當(dāng)前文章的分類和標(biāo)簽,然后查詢同分類下具有相同標(biāo)簽的10篇隨機(jī)文章。
<?php
// 獲取當(dāng)前文章的ID
$current_post_id = get_the_ID();
// 獲取當(dāng)前文章的分類
$current_post_categories = wp_get_post_categories($current_post_id);
// 獲取當(dāng)前文章的標(biāo)簽
$current_post_tags = wp_get_post_tags($current_post_id);
// 如果有分類和標(biāo)簽
if (!empty($current_post_categories) && !empty($current_post_tags)) {
// 隨機(jī)化標(biāo)簽數(shù)組
shuffle($current_post_tags);
// 取第一個(gè)標(biāo)簽作為查詢的基礎(chǔ)
$tag_id = $current_post_tags[0]->term_id;
// 構(gòu)建查詢參數(shù)
$args = array(
'posts_per_page' => 10,
'category' => $current_post_categories[0], // 使用第一個(gè)分類
'tag_id' => $tag_id,
'post__not_in' => array($current_post_id), // 排除當(dāng)前文章
'orderby' => 'rand', // 隨機(jī)排序
);
// 查詢文章
$related_posts = new WP_Query($args);
// 如果有找到相關(guān)文章
if ($related_posts->have_posts()) {
echo '<ul>';
while ($related_posts->have_posts()) {
$related_posts->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
} else {
echo '沒有找到相關(guān)文章。';
}
// 重置文章數(shù)據(jù)
wp_reset_postdata();
} else {
echo '當(dāng)前文章沒有分類或標(biāo)簽。';
}
?>
這段代碼首先獲取當(dāng)前文章的ID,然后獲取其分類和標(biāo)簽。接著,它構(gòu)建一個(gè)查詢參數(shù)數(shù)組,其中包含了限制文章數(shù)量、指定分類、指定標(biāo)簽ID、排除當(dāng)前文章以及隨機(jī)排序的設(shè)置。使用`WP_Query`執(zhí)行這個(gè)查詢,最后循環(huán)輸出查詢到的文章標(biāo)題和鏈接。
請注意,這段代碼假設(shè)當(dāng)前文章至少有一個(gè)分類和一個(gè)標(biāo)簽。如果當(dāng)前文章沒有分類或標(biāo)簽,代碼將輸出相應(yīng)的信息。此外,代碼中使用了`shuffle`函數(shù)來隨機(jī)化標(biāo)簽數(shù)組,并使用數(shù)組的第一個(gè)元素作為查詢的基礎(chǔ),這是因?yàn)槲覀冎恍枰粋€(gè)標(biāo)簽來找到相關(guān)文章。如果你想要基于所有標(biāo)簽進(jìn)行查詢,你需要修改查詢參數(shù)以包含所有標(biāo)簽。