我无法在WP查询中进行分页工作

时间:2019-09-23 14:47:20

标签: wordpress wordpress-theming

这是我当前的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'),
) ); ?>

我用Google搜索了各种解决方案。它说到处都向数组添加“分页”,就像这样:

<?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发布查询中起作用?

1 个答案:

答案 0 :(得分:0)

我认为您缺少论点:'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();