admin管理员组文章数量:1394228
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
2 Answers
Reset to default 1I 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)
本文标签: wp queryLimit number of posts in loop
版权声明:本文标题:wp query - Limit number of posts in loop 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744657313a2618043.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论