I know how to put only 5 posts per page with pagination. But let say I have 4000 posts but I don’t want to let people to be able to see all my posts. I just want to display 20 posts in 4 pages (5 per pages).

$args = array(
    'post_type' => 'blog_posts',
    'posts_per_page' => '5',

$query = new WP_Query($args);

I consider the right way could be filtering of total number of found posts like this.

function my_custom_found_posts_limiter( $found_posts, $wp_query ) {

    $maximum_of_post_items = 100; // place your desired value here or read if from option\setting.

    if ( ! is_admin() && $wp_query->is_main_query() && $wp_query->is_post_type_archive( 'blog_posts' ) ) {
        if ( $found_posts > $maximum_of_post_items ) {
            return $maximum_of_post_items; // we return maximum amount, so pagination will be aware of this number.

    return $found_posts;
add_filter( 'found_posts', 'my_custom_found_posts_limiter', 10, 2 );

See source code here https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234

and lines after this filter is applied to have better understanding of how it will work.

NB: I've used is_main_query() conditional and is_post_type_archive meaning it will be used for main Post archive loop or CPT archive page loop, but you can adjust the way you want.

UPD: added !is_admin() - check so it will not fire in wp-admin.

  • It's working but not as expected. My pagination is restricted but if I change the page number directly in the url, the pages are still displayed. Mar 19 '20 at 7:54

You can use the post_limits filter:

function my_posts_limits( $limit, $query ) {

    if ( ! is_admin() && $query->is_main_query() ) {
        return 'LIMIT 0, 25';

    return $limit;
add_filter( 'post_limits', 'my_posts_limits', 10, 2 );

This will work for your main query and won't affect the admin.


Limit WP_Query to only X results (total, not per page)

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.