Reputation: 61
I need to output on the single wordpress post the list of posts that have the same categories of the current post. With the code below I have all the posts from the first category only. How to get posts from all post's categories (some posts have 2 or more categories).
<?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; ?>
Upvotes: 1
Views: 3950
Reputation: 1810
Try this code.
<?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,
));
?>
Upvotes: 1
Reputation: 61
Just use the wp_get_post_categories()
function to get the category ids of the current post and then use category__in
in the query.
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();
Upvotes: 1