Wordpress wp_query没有显示一些帖子

问题描述 投票:0回答:1

我试图获得一个类别的5个帖子并对它们进行分页,但我的循环没有得到一些帖子。在这种情况下,我放了5个帖子来检索,但循环只返回2,有时3。

最后,当我尝试使用分页时,它不起作用。

这是我的代码:

<?php
        // Protect against arbitrary paged values
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;


        $args = array(
            'category__in' => array( 11 ),
            'category__not_in' => '',
            'posts_per_page' => 5,
            'post_type' => 'post',
            'post_status'=>'publish',

            'paged' => $paged,
        );

        $the_query = new WP_Query($args);
        ?>

        <?php if ( $the_query->have_posts() ) : ?>

        <?php while ( $the_query->have_posts() ) : $the_query->the_post();
        $the_query->the_post();
        // Post content goes here...
        // 
        echo '
        <h3 class="tituliNota">
        <a href="'.get_permalink().'" class="noteTitle">
            <b>'.the_title( ' ', ' ', false ).'</b></a></h3>';


get_the_category();
wp_reset_postdata();
endwhile; ?>

<div class="pagination">
    <?php
    echo paginate_links( array(
        'format'  => 'page/%#%',
        'current' => $paged,
        'total'   => $the_query->max_num_pages,
        'mid_size'        => 5,
        'prev_text'       => __('&laquo; Prev Page'),
        'next_text'       => __('Next Page &raquo;')
    ) );
    ?>
</div>
php wordpress
1个回答
0
投票

主查询在加载模板之前运行,WordPress根据该查询的结果决定加载哪个模板。

你说你的默认posts_per_page设置为5,并且该类别中有2或3个帖子,因此就WordPress而言,没有第2页。您在模板中运行的自定义查询,每页不同的帖子设置与主查询无关。

解决方案是通过pre_get_posts操作在加载模板之前调整主查询。这将在你的主题的functions.php文件中

function category_posts_per_page( $query ) {
    if ( !is_admin()
        && $query->is_category()
        && $query->is_main_query() ) {
        $query->set( 'posts_per_page', 5 );
    }
}
add_action( 'pre_get_posts', 'category_posts_per_page' );
© www.soinside.com 2019 - 2024. All rights reserved.