Parbhu Bissessar Parbhu Bissessar - 1 year ago 55
PHP Question

display two categories in post per page wordpress

Hi I have this code to display only one category but I want to display category 16 and category 40. So only when the users needs to select category 16 and cat 40 then this will be display on the page:

global $post;
$args = array( 'posts_per_page' => 1, 'offset'=> 0, 'category' => 16 );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) :
setup_postdata( $post );
<div class="categoriesStyle"><?php exclude_post_categories("40"); ?></div>
<div class="first"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<div class="paddingSpace"></div>
<div class="contentText"><span style="color: #000"><?php echo intro_text(150); ?></span></div>
<hr class="style-two">
<?php endforeach;
wp_reset_postdata(); ?>

Answer Source

To include more than one category you can use cat parameter instead of category

$args = array( 'posts_per_page' => 1, 'offset'=> 0, 'cat' => '16, 40' );

Or cat__in, that accept an array of category ids

$args = array( 'posts_per_page' => 1, 'offset'=> 0, 'cat__in' => array(16, 40) );

Be carefull about offset parameter that overrides $paged parameter (that you don't actually use in the present code, but can help), WP_Query class reference at Pagination Parameters part, says:

offset (int) - number of post to displace or pass over. Warning: Setting the offset parameter overrides/ignores the paged parameter and breaks pagination (Click here for a workaround). The 'offset' parameter is ignored when 'posts_per_page'=>-1 (show all posts) is used.

Hope its helps!