我知道如何每页只放5篇文章和分页。但假设我有4000条帖子,但我不想让人们看到我所有的帖子。我只想在4页中显示20个帖子(每页5篇)。
$args = array(
'post_type' => 'blog_posts',
'posts_per_page' => '5',
);
$query = new WP_Query($args);
发布于 2020-03-18 21:21:08
我认为正确的方法是过滤这样的职位总数。
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 );
见源代码,这里是https://core.trac.wordpress.org/browser/tags/5.3/src/wp-includes/class-wp-query.php#L3234
和行后,这个过滤器被应用,以更好地理解它将如何工作。
注意:我使用了is_main_query()
条件和is_post_type_archive
,这意味着它将用于主Post归档循环或CPT存档页面循环,但您可以调整您想要的方式。
UPD:添加了!is_admin()
- check,这样它就不会在wp中触发。
发布于 2020-03-19 09:00:57
您可以使用post_limits过滤器:
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 );
这将适用于您的主要查询,不会影响管理。
https://wordpress.stackexchange.com/questions/360987
复制相似问题