1

So I am using the code below to retrieve the latest 5 posts from 5 different categories.

The problem is that it outputs the latest 5 posts from only the first category in the array, even if there are newer posts in the other 4 categories.

If I remove the first category from the array, then it simply outputs the latest 5 posts from the next category in the array. It never gets to the remaining categories.

What I wanted to do was to output the newest 5 posts from all the 5 categories combined. What can I do to fix that?

<?php
$args = array( 'posts_per_page' => 5, 'category' => 15,16,17,18,19);
$myposts = get_posts( $args ); ?>
<?php foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <?php the_title(); ?>
    <?php the_content(); ?>
<?php endforeach; wp_reset_postdata();?>
3

2 choices here, you either need to set the category as an array e.g.

$args = array( 
 'posts_per_page' => 5,
 'category' => array(15,16,17,18,19)
);

You can't just add the numbers in a list but I can't find any documentation that the category element allows multiples (as the name is category)

The other option is to use wp_query and category__in

$query = new WP_Query(
 array(
  'category__in' => array(15,16,17,18,19),
  'posts_per_page' => 5,
  'post_type' => 'post',
 )
 );
if ( $query->have_posts() ) {
 while ( $query->have_posts() ) {
  $query->the_post();
  // do something
 }
}
wp_reset_postdata();

These will get the 5 last posts from any of those categories, if you want to get a post from each of them then the query needs to be a lot different

0
1

You have a problem in the array construction. You have that :

$args = array(
    'posts_per_page' => 5,
    'category' => 15, 16, 17, 18, 19
);

And you probably need that :

$args = array(
    'posts_per_page' => 5,
    'category' => [15, 16, 17, 18, 19]
);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.