get_the_posts_navigation()WP 4.1.0

Retrieve the navigation block to the next/previous set of posts. Used on archive pages (categories, tags).

Such links can be obtained using get_next_posts_link() and get_previous_posts_link() functions.

To get navigation links for a single post, use the_post_navigation().

No Hooks.

Return

String. HTML code for the previous/next sets of posts.

Usage

get_the_posts_navigation( $args );
$args(array)

Default empty array.

Default: posts navigation arguments

  • prev_text(string)
    Anchor text to display in the previous posts link.
    Default: 'Older posts'

  • next_text(string)
    Anchor text to display in the next posts link.
    Default: 'Newer posts'

  • screen_reader_text(string)
    Screen reader text for the nav element.
    Default: 'Posts navigation'

  • aria_label(string)
    ARIA label text for the nav element.
    Default: 'Posts'

  • class(string)
    Custom class for the nav element.
    Default: 'posts-navigation'

Examples

1

#1 Output links to the previous / next set of posts

the_posts_navigation( [
	'prev_text'          => '← Prev',
	'next_text'          => 'Next →',
	'screen_reader_text' => 'My navigation',
] );
<nav class="navigation posts-navigation" role="navigation">
	<h2 class="screen-reader-text">My navigation</h2>
	<div class="nav-links">
		<div class="nav-previous">
			<a href="http://example.com/page/3/">← Prev</a>
		</div>
		<div class="nav-next">
			<a href="http://example.com/">Next →</a>
		</div>
	</div>
</nav>

Notes

  • Global. WP_Query. $wp_query WordPress Query object.

Changelog

Since 4.1.0 Introduced.
Since 5.3.0 Added the aria_label parameter.
Since 5.5.0 Added the class parameter.

get_the_posts_navigation() code WP 6.6.2

function get_the_posts_navigation( $args = array() ) {
	global $wp_query;

	$navigation = '';

	// Don't print empty markup if there's only one page.
	if ( $wp_query->max_num_pages > 1 ) {
		// Make sure the nav element has an aria-label attribute: fallback to the screen reader text.
		if ( ! empty( $args['screen_reader_text'] ) && empty( $args['aria_label'] ) ) {
			$args['aria_label'] = $args['screen_reader_text'];
		}

		$args = wp_parse_args(
			$args,
			array(
				'prev_text'          => __( 'Older posts' ),
				'next_text'          => __( 'Newer posts' ),
				'screen_reader_text' => __( 'Posts navigation' ),
				'aria_label'         => __( 'Posts' ),
				'class'              => 'posts-navigation',
			)
		);

		$next_link = get_previous_posts_link( $args['next_text'] );
		$prev_link = get_next_posts_link( $args['prev_text'] );

		if ( $prev_link ) {
			$navigation .= '<div class="nav-previous">' . $prev_link . '</div>';
		}

		if ( $next_link ) {
			$navigation .= '<div class="nav-next">' . $next_link . '</div>';
		}

		$navigation = _navigation_markup( $navigation, $args['class'], $args['screen_reader_text'], $args['aria_label'] );
	}

	return $navigation;
}