WordPress自定义循环分页 [英] Wordpress custom loop pagination

查看:91
本文介绍了WordPress自定义循环分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多个循环结构中编码了自定义循环:

$q = get_posts( $args );
// Run your loop
echo '<div class="row">';
$i = 0; 
foreach ( $q as $post ) : setup_postdata( $post );
  $i++; 
  if ($i%4==0)
    echo '</div><div class="row">';
  get_template_part('loop');
endforeach;
wp_bs_pagination();
wp_reset_postdata();

,除了我在加载分页中添加了wp_bs_pagination();.它只会在每页上重复同一组帖子.有什么建议吗?

except for I added wp_bs_pagination(); to load pagination. It only repeat the same set of posts o every page. Any suggestions?

推荐答案

请勿对分页查询使用. get_posts适用于非分页查询,但不适用于分页查询.

Do not use get_posts() for paginated queries. get_posts works well for non-paginated queries, but not paginated queries.

问题是,get_posts仅从WP_Query返回$posts属性,而不返回完整的对象.此外,get_posts()'no_found_rows'=> true传递到WP_Query,从而合法地中断了分页.

The issue is, get_posts only returns the $posts property from WP_Query and not the complete object. Furthermore, get_posts() passes 'no_found_rows'=> true to WP_Query which legally breaks pagination.

因为get_posts使用WP_Query,所以我们最好使用WP_Query,它返回分页查询所需的所有内容.请记住,我们需要在查询中添加paged参数以对其进行分页

Because get_posts uses WP_Query, we might as well use WP_Query which returns everything we need to paginate our query. Just remember, we need to add the paged parameter to the query in order to page it

我们可以按照以下方式重写您的查询

We can rewrite your query as follow

$args= [
    'paged' => get_query_var( 'paged' ),
    // Add any additional arguments here
];
$q = new WP_Query( $args );
// Run your loop

if( $q->have_posts() ) { 

    echo '<div class="row">';
    $i=0; 

    while ( $q->have_posts() ) {
    $q->the_post();
        $i++; 
        if($i%4==0)
            echo '</div><div class="row">';

        get_template_part('loop');

    }
    wp_bs_pagination();
    wp_reset_postdata();
}

您将需要以某种方式将$q->max_num_pages传递给wp_bs_pagination()来将分页设置为您的自定义查询,但是我不知道该函数,因此无法为您提供确切的解决方案.

You will need to somehow pass $q->max_num_pages to wp_bs_pagination() to set pagination to your custom query, but I do not know the function, so I cannot give you an exact solution on this.

这篇关于WordPress自定义循环分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆