简体   繁体   中英

Wordpress wp_query not showing some posts

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>

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' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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