好问题,这与获取相关类别或标签有点不同,尽管仍然使用类似的前提。有几种方法可以做到这一点,但最简单的方法之一可能是使用自定义函数,该函数利用WP_Query
. 将以下代码添加到您的functions.php
文件中。
// Create a query for the custom taxonomy
function related_posts_by_taxonomy( $post_id, $taxonomy, $args=array() ) {
$query = new WP_Query();
$terms = wp_get_object_terms( $post_id, $taxonomy );
// Make sure we have terms from the current post
if ( count( $terms ) ) {
$post_ids = get_objects_in_term( $terms[0]->term_id, $taxonomy );
$post = get_post( $post_id );
$post_type = get_post_type( $post );
// Only search for the custom taxonomy on whichever post_type
// we AREN'T currently on
// This refers to the custom post_types you created so
// make sure they are spelled/capitalized correctly
if ( strcasecmp($post_type, 'locations') == 0 ) {
$type = 'videos';
} else {
$type = 'locations';
}
$args = wp_parse_args( $args, array(
'post_type' => $type,
'post__in' => $post_ids,
'taxonomy' => $taxonomy,
'term' => $terms[0]->slug,
) );
$query = new WP_Query( $args );
}
// Return our results in query form
return $query;
}
显然,您可以更改此函数中的任何内容以获得您正在寻找的确切结果。查看http://codex.wordpress.org/Class_Reference/WP_Query以供进一步参考。
有了它,您现在可以访问该related_posts_by_taxonomy()
功能,您可以在其中传递您想要查找相关帖子的任何分类。因此,在您single.php
或任何用于自定义帖子类型的模板中,您可以执行以下操作:
<h4>Related Posts</h3>
<ul>
<?php $related = related_posts_by_taxonomy( $post->ID, 'Video_Categories' );
while ( $related->have_posts() ): $related->the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; ?>
</ul>