首页 > 解决方案 > 我无法在 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 帖子查询中工作?

标签: wordpresswordpress-theming

解决方案


我认为你错过了这个论点:'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();

推荐阅读