如何限制wp查询循环中的帖子总数?

时间:2017-02-03 作者:Bhojendra Rauniyar

我想每页显示5篇文章,但限制循环中产生的文章总数。

$args = array(
  \'post_type\' => \'post\',
  \'posts_per_page\' => 5,
  \'paged\' => $paged
);
假设我有100篇文章,上面的查询参数每页显示5篇文章,我可以看到20页。那么,我该如何限制所生成的帖子的总数,以便在我的情况下只显示3页?我不需要整整3页来显示,但我想限制总的帖子,比如25篇,23篇。所以,如果我想限制12篇文章,那么我可以在第一页看到5篇文章,在第二页看到5篇文章,在最后一页看到剩下的2篇文章。

5 个回复
SO网友:Milo

您可以使用found_posts filter 更改WordPress报告从查询中查找的帖子数。

add_filter( \'found_posts\', \'wpd_found_posts\', 10, 2 );
function wpd_found_posts( $found_posts, $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        return 25;
    }
}

SO网友:Gonzoarte

使用post_limits 挂钩优先级为2。。。

function my_posts_limit( $limit, $query ) {
  return \'LIMIT 0, 25\';
}
add_filter( \'post_limits\', \'my_posts_limit\', 10, 2 );

SO网友:Ravi Patel

post_limits

/**
 * Limit the main query search results to 25.
 *
 * We only want to filter the limit on the front end of the site, so we use
 * is_admin() to check that we aren\'t on the admin side.
 *
 * We also only want to filter the main query, so we check that this is it
 * with $query->is_main_query().
 *
 * Finally, we only want to change the limit for searches, so we check that
 * this query is a search with $query->is_search().
 *
 * @see http://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits
 * 
 * @param string $limit The \'LIMIT\' clause for the query.
 * @param object $query The current query object.
 *
 * @return string The filtered LIMIT.
 */
function wpcodex_filter_main_search_post_limits( $limit, $query ) {

    if ( ! is_admin() && $query->is_main_query() && ($query->is_search() || $query->is_home()) ){
        return \'LIMIT 0, 25\';
    }

    return $limit;
}
add_filter( \'post_limits\', \'wpcodex_filter_main_search_post_limits\', 10, 2 );
SO网友:Anand

您可以通过两种方式设置post限制:

1) wp-admin > Settings > Reading

2) By passing the argument query \'numberposts\' => 5

SO网友:Gonzoarte

使用\'numberposts\' 参数

$args = array(
\'post_type\' => \'post\',
\'numberposts\' => 25,
\'posts_per_page\' => 5,
\'paged\' => $paged
);

Exemple at the Developer\'s Codex

相关推荐

Increase offset while looping

我正在编写一个自定义帖子插件,它将自定义帖子分组显示为选项卡。每组4个岗位。是否可以编写一个偏移量随每次循环而增加的查询?因此,结果将是:-第一个查询显示从1到4的帖子-第二个查询显示从5到8的帖子-第三个查询显示从9到12的帖子等。 <div class=\"official-matters-tabs\"> <?php $args = array(\'post_type\' => \'official-matters\', \'showp