尝试以下操作:
在单个视图上,您需要使用get_the_terms()
而不是get_terms()
. 这样,您就得到了实际分配给该职位的术语,而不是现有的所有术语。
$post_type = \'mp3\';
$tax = \'post_tag\';
$post_count = 5;
$counter = 0;
$tax_terms = get_the_terms($post->ID, $tax);
if ($tax_terms) {
foreach ($tax_terms as $tax_term) {
$args = array(
\'post_type\' => $post_type,
"$tax" => $tax_term->slug,
\'post_status\' => \'publish\',
\'orderby\' => \'rand\',
\'posts_per_page\' => 5
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo \'<ul id="related-posts" class="item-list">\';
echo \'<h6>Related Posts</h6>\';
while ($my_query->have_posts() && $counter < $post_count) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php
$counter += 1;
endwhile;
echo \'</ul>\';
}
wp_reset_query();
}
}
NOTE: 此代码将生成多个相关帖子列表。如果当前帖子分配了2个标签,您将得到2个相关帖子的列表。如果您希望从两个标签组合中找到一个相关帖子列表,您可以使用以下内容:
$post_type = \'mp3\';
$tax = \'post_tag\';
$post_count = 5;
$counter = 0;
$tax_terms = get_the_terms($post->ID, $tax);
if ($tax_terms) {
$tax_term_ids = array();
foreach ($tax_terms as $tax_term) {
$tax_term_ids[] = $tax_term->term_id;
}
$args = array(
\'post_type\' => $post_type,
"tax_query" => array(
array(
\'taxonomy\' => $tax,
\'terms\' => $tax_term_ids,
)
),
\'post_status\' => \'publish\',
\'orderby\' => \'rand\',
\'posts_per_page\' => 5
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo \'<ul id="related-posts" class="item-list">\';
echo \'<h6>Related Posts</h6>\';
while ($my_query->have_posts() && $counter < $post_count) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php
$counter += 1;
endwhile;
echo \'</ul>\';
}
wp_reset_query();
}