I'm not sure whether it's a bug or i'm doing something wrong, but it doesn't seem like posts_per_page works at all when using category__in.

My query is below, even though I've set posts_per_page to 1, it's still showing all posts.

$posts = new WP_Query(array(
    'post_type'      => 'post',
    'category__in'   => wp_get_post_categories($post->ID),
    'posts_per_page' => 1,
    'post__not_in'   => array($post->ID)

Any ideas?

  • Wordpress has a setting for this, found in the admin area under SETTINGS -> READING -> Blog pages show at most You can use this instead of custom-modifying your queries. It may make it a little easier to maintain your project down the road. – vikrant zilpe Nov 29 '18 at 9:11
  • @vikrantzilpe It's a custom query, which is getting only one post - I'm pretty sure that setting global post count isn't a solution in this case... – Krzysiek Dróżdż Nov 29 '18 at 9:13

i am testing your code on my dev site and it returns only 1 result (although there are 3 items in the same category), so your code seems to be fine, maybe there is some other filter applied which ignores the posts_per_page param.

You can try using suppress_filters => true param in your WP_Query args list or use the get_posts() function instead of WP_Query as the function has supress_filters enabled by default so the code would be

$posts = get_posts(array( 'post_type' => 'post', 'category__in' => wp_get_post_categories($post->ID), 'posts_per_page' => 1, 'post__not_in' => array($post->ID) ));

Hope this helps.

| improve this answer | |
  • 1
    Thank you, I was modifying the limit via pre_get_posts elsewhere. I updated that to only affect the main query using $query->is_main_query(). – KeironLowe Nov 29 '18 at 9:31
  • Sure, no problem :). – Greg Winiarski Nov 29 '18 at 11:02

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.