douxi2011 2019-02-28 21:21
浏览 70
已采纳

Wordpress wp_query没有显示一些帖子

I'm trying to get 5 posts of one category and paginate them, but my loop doesn't get some posts. In this case, I put 5 posts to retrieve but the loop only returns 2 and sometimes 3.

Finally, when I'm trying to use pagination it doesn't work.

Here is my code:

<?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>
  • 写回答

1条回答 默认 最新

  • dtpfia3334 2019-02-28 22:02
    关注

    The main query runs before the template is loaded, and WordPress decides what template to load based on the results of that query.

    You say your default posts_per_page is set to 5, and there are 2 or 3 posts in that category, so as far as WordPress knows, there is no page 2. Your custom query that you run in the template with a different posts per page setting is unrelated to the main query.

    The solution is to make adjustments to the main query before the template is loaded, via the pre_get_posts action. This would go in your theme's functions.php file

    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' );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘