[英]Get wordpress posts from the same categories
我需要 output 上的单个 wordpress 发布与当前帖子具有相同类别的帖子列表。 使用下面的代码,我只有第一类的所有帖子。 如何从所有帖子的类别中获取帖子(有些帖子有 2 个或更多类别)。
<?php
global $post;
$current_category = get_the_category();
$same_category = new WP_Query(array(
'cat' => $current_category[0]->cat_ID,
'post__not_in' => array($post->ID),
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => -1,
));
?>
<?php while ( $same_category->have_posts() ) : $same_category->the_post(); ?>
<li>
<div class="borderline">
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</div>
</li>
<?php endwhile; ?>
试试这个代码。
<?php
global $post;
$categories_id = array();
$current_category = get_the_category();
foreach($current_category as $cc){
$categories_id[] = $cc->term_id;
}
$same_category = new WP_Query(array(
'cat' => $categories_id,
'post__not_in' => array($post->ID),
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => -1,
));
?>
只需使用wp_get_post_categories()
function 获取当前帖子的类别 ID,然后在查询中使用category__in
。
get_header();
while ( have_posts() ) {
the_post();
// Show current posts info
the_title();
the_content();
// Show posts of current post categories
$post_id = get_the_ID();
$post_categories = wp_get_post_categories( $post_id );
$query_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category__in' => $post_categories,
);
$query_res = new WP_Query($query_args);
if ( $query_res->have_posts() ) {
while ( $query_res->have_posts() ) {
$query_res->the_post();
the_title();
}
} else {
echo 'Nothing to show!';
}
wp_reset_postdata();
}
get_footer();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.