WP Query - Posts Per Page not working in combination with category__in

admin2025-06-06  2

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?

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?

Share Improve this question edited Nov 29, 2018 at 9:12 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Nov 29, 2018 at 8:37 KeironLoweKeironLowe 1335 bronze badges 2
  • 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 Commented Nov 29, 2018 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ż Commented Nov 29, 2018 at 9:13
Add a comment  | 

1 Answer 1

Reset to default 1

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749143113a316732.html

最新回复(0)