最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Limit number of posts in loop

programmeradmin6浏览0评论

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 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);
Share Improve this question asked Mar 18, 2020 at 20:18 user3492770user3492770 771 silver badge8 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

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/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.

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.

https://codex.wordpress/Plugin_API/Filter_Reference/post_limits

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

发布评论

评论列表(0)

  1. 暂无评论