Search code examples
phpwordpressposts

list wordpress posts from current category and


Using this code from here: http://www.snilesh.com/resources/wordpress/wordpress-recent-posts-from-current-same-category/

<h3>Recently Post From Same Category</h3>
<ul>
<?php
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;
$myposts = get_posts(array('numberposts' => 5, 'offset' => 0,
'category__in' => array($category), 'post__not_in' =>
array($post->ID),'post_status'=>'publish'));
foreach($myposts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a>
</li>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
</ul>

I'm able to display all the posts from the current category. What I would like to display is all the posts from the current category AND category 186.


Solution

  • If you want to show posts that are both in the current category and category 186, use category__and instead:

    $myposts = get_posts(array(
        'numberposts' => 5,
        'offset' => 0,
        'category__and' => array($category, 186),
        'post__not_in' => array($post->ID),
        'post_status'=>'publish'
    ));
    

    For more details: WP_Query - Category Parameters.

    P.S.: get_posts() internally uses the WP_Query class to fetch posts so its parameters are the same.