【问题标题】:How to Check if WP_Query has next page by Wordpress way?如何通过 Wordpress 方式检查 WP_Query 是否有下一页?
【发布时间】:2020-03-06 09:12:18
【问题描述】:

sn-p:

$query = new \WP_Query(
            [
                'post_type'      => 'post',
                'post_status'    => 'publish',
                'posts_per_page' => 3,
                'paged'          => $paged,
            ]
        );
$query->found_posts; // all of the posts

只有我研究过的方法是每次对代码进行硬编码。

$posts_per_page = (int) $this->query_vars['posts_per_page'];
$has_next = $paged < ceil( (float) $query->found_posts / $posts_per_page );

问题是在我想计算 has_next 的所有地方重复代码。

这个问题可以通过扩展WP_Query类并添加方法has_next_page来解决。 但这个解决方案比问题复杂得多。

是否有 Wordpress 方法可以确定 WP_Query 是否有下一页而无需重新发明轮子?

【问题讨论】:

  • 您也可以对照 maxof wp_query 检查当前页面,或者正如您所说的扩展它,您知道没有办法。
  • 扩展类只会在你实例化你自己的查询对象的地方起作用,这意味着如果你需要它来进行主查询,它一开始就没有用。我可能只是在这里写一个简单的独立函数,它获取一个可选的 WP_Query 实例传入,如果没有传入则回退到全局实例 - 并返回上述“公式”的结果。
  • @CBroe,查询不是主查询
  • 这就是为什么我说,“获取传入的可选 WP_Query 实例,[and] 如果没有传入则回退到全局实例” ...您只需调用如果你想在主查询中使用 query_has_next(),函数 query_has_next($query) 对于你这里的情况。

标签: php wordpress pagination


【解决方案1】:
Did you check the following method?

In the template file

$search_args = array(

'post_type'      => 'post',
'post_status'    => 'publish',
'posts_per_page' => 3,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
);
$search_query = new WP_Query($search_args);


$big = 999999999;

$pages = paginate_links( array(
  'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
  'format' => '?paged=%#%',
  'current' => max( 1, get_query_var('paged') ),
  'total' => $search_query->max_num_pages,


) );

if($pages){
    // exists
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2018-09-25
    • 2011-07-25
    相关资源
    最近更新 更多