Pagination with get_posts

Sort of. The fact is that get_posts is limited when we want to achieve trustable and easy pagination, so we will use WP_Query and replicate how get_posts is constructed.

$new_query = new WP_Query();
$posts = $new_query->query($query_args);
$out = ”;

if( $posts ) {
global $post, $paged;

foreach ($posts as $post) {
    //do post stuff
} wp_reset_postdata();

out .= paginate_links( array(
    'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
    'format' => '?paged=%#%',
    'current' => max( 1, $paged ),
    'total' => $new_query->max_num_pages


return $out;

You’ll notice that this code is built like if it was used in a shortcode but you can adapt it to template fashion.

Leave a Reply