get_next_posts_page_link()WP 2.0.10

Gets the URL for the list of previously published posts within the current query (pagination link).

Since posts are usually sorted in reverse order (later posts are shown first), this function typically points to the later posts.

Works on all pages except is_single(). That is, the condition is_single() should not trigger.

Works based on the global variable global $paged;.

1 time — 0.0050561 sec (very slow) | 50000 times — 5.91 sec (fast)

No Hooks.

Returns

String|null. URL of the archive of previously published posts. Will return null if there is no next page.

Usage

get_next_posts_page_link( $max_page );
$max_page(int)
How many total pagination pages are possible. If you specify, for example, 5 here and the current pagination page is 6 or more, the function will return nothing.
Default: 0

Examples

0

#1 Display the button "Show more" with url

For example, we have a post type called figurants and in this archive, we want to display a button to the next page of the pagination.

Let's say we are now on pagination page 2:

<?php if ( $next_url = get_next_posts_page_link( $GLOBALS['wp_query']->max_num_pages ?: 1 ) ): ?>
	<button class="btn" type="button"  
			data-url="<?= $next_url ?>">Show more
	</button>
<?php endif; ?>

We get it:

<button class="btn" type="button"  
		data-url="https://example.com/figurants/page/3/">Show more
</button>

Notice how the check is done. This is because if the function does not specify the maximum number of pagination pages or specify 0, it will assume there is an infinite number and always return a link even if the next pagination page does not actually exist. When you use WP_Query{} (this includes the basic query), the property max_num_pages contains the maximum number of pagination pages, but if there is only one pagination page, it will be 0, we have to replace it with 1 to make get_next_posts_page_link() function work correctly.

Notes

  • Global. Int. $paged

Changelog

Since 2.0.10 Introduced.

get_next_posts_page_link() code WP 6.9.1

function get_next_posts_page_link( $max_page = 0 ) {
	global $paged;

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

		$next_page = (int) $paged + 1;

		if ( ! $max_page || $max_page >= $next_page ) {
			return get_pagenum_link( $next_page );
		}
	}
}