繁体   English   中英

WordPress的wp_query不显示一些帖子

[英]Wordpress wp_query not showing some posts

我正在尝试获得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>

主查询在加载模板之前运行,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' );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM