Search code examples
phpwordpresspaginationcustom-wordpress-pageswordpress-hook

Display latest 100 posts with pagination of 5 posts per page in wordpress using WP Query


My website has more than 5000 posts and I am trying to display the latest 100 posts in a separate page with pagination(5 posts per page).

<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $paged
);
$wp_query = new WP_Query($args);
if( $wp_query->have_posts() ) : 
while( $wp_query->have_posts() ) : $wp_query->the_post();
get_template_part( 'template-parts/content', get_post_type() );
endwhile;
the_posts_navigation(); 
wp_reset_postdata();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
?>

I am using the above code which displays 5 posts per page but I could find a way to restrict the total posts count to 100. I went through various blog articles and various SO threads but couldn't find any solution for this.

There were few threads that say, using 'numberposts' => 100 will help. But that didn't help either. Thanks in advance.


Solution

  • You can calculate the limit as like:

    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    $args = array(
    'post_type' => 'post',
    'posts_per_page' => 5,
    'paged' => $paged
    );
    if($args['posts_per_page'] * $args['paged'] <= 100){
        $wp_query = new WP_Query($args);
        if( $wp_query->have_posts() ) : 
        while( $wp_query->have_posts() ) : $wp_query->the_post();
        get_template_part( 'template-parts/content', get_post_type() );
        endwhile;
        the_posts_navigation(); 
        wp_reset_postdata();
        else :
        get_template_part( 'template-parts/content', 'none' );
        endif;
    }