How to limit total number of posts in wp query loop?

I want to show 5 posts per page but limit total number of posts being resulted in a loop.

$args = array(
  'post_type' => 'post',
  'posts_per_page' => 5,
  'paged' => $paged
);

Suppose, I have 100 posts and the above query args will display 5 posts per page and I can see 20 pages. So, how can I limit the total number of posts being resulted so that in my condition it would only show 3 pages? I’m not needing exactly 3 pages to show but wanted to limit the total post like 25 posts, 23 posts. So, if I wanted to limit 12 posts then I can see 5 posts on first page, 5 posts on second page and remaining 2 posts on last page.

5 Answers
5

You can use the found_posts filter to alter the number of posts WordPress reports finding from a query.

add_filter( 'found_posts', 'wpd_found_posts', 10, 2 );
function wpd_found_posts( $found_posts, $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        return 25;
    }
}

Leave a Comment