get_next_posts_link()WP 2.7.0

Gets the HTML link to the list of previously published posts within the current query (pagination link).

Since posts are usually sorted in reverse chronological order (later posts are shown first), get_next_posts_link() typically points to later posts. If you need to get a link to earlier (previous) posts, use the opposite function get_previous_posts_link(), which points to newer (latest) posts.

Hooks from the function

Returns

String|null. HTML link if it was successfully retrieved or null.

Usage

get_next_posts_link( $label, $max_page );
$label(string)
Text of the link. Default is "next page »" (Next Page »).
Default: __( 'Next Page »' )
$max_page(int)
Limit, the number of pages on which the link will be displayed. Default 0 - no limit.
Default: $wp_query->max_num_pages

Examples

0

#1 Basic use

<?php echo get_next_posts_link(); ?>
0

#2 Custom link text

<?php echo get_next_posts_link( 'Next page' ); ?>
0

#3 Custom text and number of pages

<?php echo get_next_posts_link( 'To the next page', 4 ); ?>
0

#4 Using together with the WP_Query arbitrary loop

Add $max_pages parameter when you create a loop with WP_Query. To get the number of all pages, you can use "max_num_pages" property of WP_Query object:

<?php
// define the current pagination page
// use the 'page' parameter instead of paged on the main page if it is static
$paged = get_query_var( 'paged' ) ?: 1;

// query: output posts from category 1
$the_query = new WP_Query( 'cat=1&paged=' . $paged );

if ( $the_query->have_posts() ){

	// loop
	while ( $the_query->have_posts() ){
		$the_query->the_post(); // set global variable $post
		the_title();
	}

	// get_next_posts_link() with page limit (second parameter)
	echo get_next_posts_link( 'Early posts', $the_query->max_num_pages );
	echo get_previous_posts_link( 'New posts' );

	// Clean up global variables
	wp_reset_postdata();

} 
else {
	echo '<p>No posts matching the query were found.</p>';
}
?>

Notes

  • Global. Int. $paged
  • Global. WP_Query. $wp_query WordPress Query object.

Changelog

Since 2.7.0 Introduced.

get_next_posts_link() code WP 6.9

function get_next_posts_link( $label = null, $max_page = 0 ) {
	global $paged, $wp_query;

	if ( ! $max_page ) {
		$max_page = $wp_query->max_num_pages;
	}

	if ( ! $paged ) {
		$paged = 1;
	}

	$next_page = (int) $paged + 1;

	if ( null === $label ) {
		$label = __( 'Next Page &raquo;' );
	}

	if ( ! is_single() && ( $next_page <= $max_page ) ) {
		/**
		 * Filters the anchor tag attributes for the next posts page link.
		 *
		 * @since 2.7.0
		 *
		 * @param string $attributes Attributes for the anchor tag.
		 */
		$attr = apply_filters( 'next_posts_link_attributes', '' );

		return sprintf(
			'<a href="%1$s" %2$s>%3$s</a>',
			next_posts( $max_page, false ),
			$attr,
			preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&#038;$1', $label )
		);
	}
}