get_posts_nav_link()WP 2.8.0

Retrieves the post pages link navigation for previous and next pages.

Used By: posts_nav_link()

No Hooks.

Return

String. The posts link navigation.

Usage

get_posts_nav_link( $args );
$args(string|array)

Arguments to build the post pages link navigation.

Default: array()

  • sep(string)
    Separator character.
    Default: '—'

  • prelabel(string)
    Link text to display for the previous page link.
    Default: '« Previous Page'

  • nxtlabel(string)
    Link text to display for the next page link.
    Default: 'Next Page »'

Examples

0

#1 Demonstration of what the function outputs

echo get_posts_nav_link();

Displays:

<a href="link">Previous page</a> - <a href="link">Next page"</a>
0

#2 Place the links in the middle and pass the parameters

To do this, wrap them in a DIV and give it the text-align:center property:

$links_html = get_posts_nav_link( array(
	'sep' => ' . ',
	'prelabel' => 'Previous page',
	'nxtlabel' => 'Next page'
) );

echo "<div style='text-align:center;'>$links_html</div>";
0

#3 Instead of texts: "Previous page", "Next page", you can use images

$links_html = get_posts_nav_link( array(
	'sep' => ' . ',
	'prelabel' => '<img src="' . get_stylesheet_directory_uri() . '/images/prev.jpg" />',
	'nxtlabel' => '<img src="' . get_stylesheet_directory_uri() . '/images/next.jpg" />'
) );

Notes

  • Global. WP_Query. $wp_query WordPress Query object.

Changelog

Since 2.8.0 Introduced.

Code of get_posts_nav_link() WP 5.9.3

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

	$return = '';

	if ( ! is_singular() ) {
		$defaults = array(
			'sep'      => ' &#8212; ',
			'prelabel' => __( '&laquo; Previous Page' ),
			'nxtlabel' => __( 'Next Page &raquo;' ),
		);
		$args     = wp_parse_args( $args, $defaults );

		$max_num_pages = $wp_query->max_num_pages;
		$paged         = get_query_var( 'paged' );

		// Only have sep if there's both prev and next results.
		if ( $paged < 2 || $paged >= $max_num_pages ) {
			$args['sep'] = '';
		}

		if ( $max_num_pages > 1 ) {
			$return  = get_previous_posts_link( $args['prelabel'] );
			$return .= preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&#038;$1', $args['sep'] );
			$return .= get_next_posts_link( $args['nxtlabel'] );
		}
	}
	return $return;

}