wordpress - 我无法在 WP 查询中进行分页
问题描述
这是我当前的 wordpress 帖子查询的样子:
<?php
$new_loop = new WP_Query( array(
'post_type' => 'news',
'posts_per_page' => 5
) );
?>
我想在其中添加以下分页:
<?php the_posts_pagination( array(
'mid_size' => 2,
'prev_text' => __( 'Prev'),
'next_text' => __( 'Next'),
) ); ?>
我搜索了各种解决方案。到处都说要向数组添加“分页”,如下所示:
<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;**
$new_loop = new WP_Query( array(
'post_type' => 'news',
'paged' => $paged,**
'posts_per_page' => 5 // put number of posts that you'd like to display
) );
?>
但是,这不起作用。如何让分页在自定义 wordpress 帖子查询中工作?
解决方案
我认为你错过了这个论点:'current' => max( 1, get_query_var( 'paged' ) )
运行循环后,您可以在主题中添加此函数(functions.php 或其他地方):
if ( ! function_exists( 'custom_pagination' ) ) {
function custom_pagination( $args = array(), $class = 'pagination' ) {
if ( $GLOBALS['wp_query']->max_num_pages <= 1 ) {
return;
}
$args = wp_parse_args(
$args,
array(
'mid_size' => 3,
'prev_next' => true,
'prev_text' => __( 'Previous', 'theme' ),
'next_text' => __( 'Next', 'theme' ),
'screen_reader_text' => __( 'Posts navigation', 'theme' ),
'type' => 'array',
'current' => max( 1, get_query_var( 'paged' ) ),
//'total' => $the_query->max_num_pages,
)
);
$links = paginate_links( $args );
?>
<nav aria-label="<?php echo $args['screen_reader_text']; ?>">
<ul class="pagination">
<?php
foreach ( $links as $key => $link ) {
?>
<li class="page-item <?php echo strpos( $link, 'current' ) ? 'active' : ''; ?>">
<?php echo str_replace( 'page-numbers', 'page-link', $link ); ?>
</li>
<?php
}
?>
</ul>
</nav>
<?php
}
}
然后最后在您需要的任何模板中调用它:
custom_pagination();
推荐阅读
- rust - 闭包不能返回引用吗?
- tensorflow - 不规则张量上的 Keras 自定义层以降低维度
- java - Java:创建预定义颜色数组
- javascript - 评估函数中的 JS 无法执行
- deployment - Bitbucket Piplines:从子目录上传到登台/生产服务器
- angular - Angular - 为什么每次我发出新值时都会调用 ngOnInit?
- node.js - 无法在 Google Directory API 中获取根 Orgunit
- gem5 - 如何为 gem5 添加新架构?
- java - 如何根据 Vaadin 14 中的数据为网格的行或单元格着色
- c++ - 为可执行文件分配更多 RAM