Using WordPress ‘get_next_posts_link()’ PHP function

The get_next_posts_link() WordPress PHP function retrieves the next posts page link.

Usage

get_next_posts_link( $label, $max_page )

Example:

echo get_next_posts_link( 'Next Page', 3 );

Output: A link to the next page with the text “Next Page” and a maximum of 3 pages.

Parameters

  • $label (string) – Optional. Content for link text. Default: null
  • $max_page (int) – Optional. Max pages. Default: 0

More information

See WordPress Developer Resources: get_next_posts_link()

Examples

Basic usage

Retrieve the next posts page link with default label and maximum pages.

echo get_next_posts_link();

Custom label

Retrieve the next posts page link with a custom label.

echo get_next_posts_link( 'Go to the next page' );

Custom label and maximum pages

Retrieve the next posts page link with a custom label and maximum pages.

echo get_next_posts_link( 'Go to the next page', 4 );

Usage with WP_Query

Retrieve the next posts page link when querying the loop with WP_Query. Pass the $max_page parameter to the get_next_posts_link() function.

$paged = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;
$the_query = new WP_Query( 'cat=1&paged=' . $paged );

if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        the_title();
    endwhile;

    echo get_next_posts_link( 'Older Entries', $the_query->max_num_pages );
    echo get_previous_posts_link( 'Newer Entries' );

    wp_reset_postdata();
else :
    echo '<p>No posts matched your criteria.</p>';
endif;

Usage with custom post type

Retrieve the next posts page link for a custom post type.

$paged = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;
$the_query = new WP_Query( array(
    'post_type' => 'my_custom_post_type',
    'paged'     => $paged
) );

if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        the_title();
    endwhile;

    echo get_next_posts_link( 'Older Entries', $the_query->max_num_pages );
    echo get_previous_posts_link( 'Newer Entries' );

    wp_reset_postdata();
else :
    echo '<p>No posts matched your criteria.</p>';
endif;