我知道如何把每页只有5篇文章分页。但假设我有4000个帖子,但我不想让人们看到我所有的帖子。我只想在4页中显示20篇文章(每页5篇)。
$args = array(
\'post_type\' => \'blog_posts\',
\'posts_per_page\' => \'5\',
);
$query = new WP_Query($args);
我知道如何把每页只有5篇文章分页。但假设我有4000个帖子,但我不想让人们看到我所有的帖子。我只想在4页中显示20篇文章(每页5篇)。
$args = array(
\'post_type\' => \'blog_posts\',
\'posts_per_page\' => \'5\',
);
$query = new WP_Query($args);
我认为正确的方法可能是过滤像这样找到的帖子总数。
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应用此过滤器后的行可以更好地了解其工作方式。
NB:我用过is_main_query()
有条件和is_post_type_archive
这意味着它将用于主后期归档循环或CPT归档页面循环,但您可以根据需要进行调整。
UPD:已添加!is_admin()
- 检查以使其不会在wp admin中激发。
您可以使用post\\u 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://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits
嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post