我在这个主题上发现了其他帖子,但它对我没有帮助。 如果我将此代码添加到我的代码中,是否可以显示与当前帖子相同类别的相关帖子?
我发布下面的代码来展示我想要实现的目标:
<?php
$related = get_posts( array( 'category__in' =>
wp_get_post_categories($post->ID), 'numberposts' => 5, 'post__not_in' => array($post->ID) ) );
if( $related )
foreach( $related as $post ) {
setup_postdata($post); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<?php }
wp_reset_postdata(); ?>
答案 0 :(得分:0)
显示同一类别的相关帖子
$terms = get_the_terms( $post->ID, 'category' );
if ( empty( $terms ) ) $terms = array();
$term_list = wp_list_pluck( $terms, 'slug' );
$related_args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'post_status' => 'publish',
'post__not_in' => array( $post->ID ),
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $term_list
)
)
);
$my_query = new WP_Query($related_args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
the_title();
echo "<br>";
endwhile;
}
wp_reset_query();