get_next_posts_link()WP 2.7.0

Retrieves the next posts page link.

Hooks from the function

Return

String|null. HTML-formatted next posts page link.

Usage

get_next_posts_link( $label, $max_page );
$label(string)
Content for link text.
Default: null
$max_page(int)
Max 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.4.3

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