get_previous_posts_link()WP 2.7.0

Gets an HTML link (<a>) to the page with previous posts (newer posts).

Since posts in WordPress are displayed in reverse chronological order

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

Hooks from the function

Returns

String|null. A link to a group of previous posts in pagination.

Usage

get_previous_posts_link( $label );
$label(string)
Text of the link.
Default: __( '« Previous Page' )

Examples

0

#1 Let's write the link to the previous posts into a variable and display it

$prev = get_previous_posts_link();
echo $prev;
0

#2 Removing Trailing Slashes from Prev & Next links

If you are using no-end-trailing slashes for your URLs. You may add following filter in your functions file to remove trailing slashes from generated links from get_previous_posts_links() function.

add_filter( 'get_pagenum_link', 'user_trailingslashit' );

Notes

  • Global. Int. $paged

Changelog

Since 2.7.0 Introduced.

get_previous_posts_link() code WP 6.9.1

function get_previous_posts_link( $label = null ) {
	global $paged;

	if ( null === $label ) {
		$label = __( '&laquo; Previous Page' );
	}

	if ( ! is_single() && $paged > 1 ) {
		/**
		 * Filters the anchor tag attributes for the previous posts page link.
		 *
		 * @since 2.7.0
		 *
		 * @param string $attributes Attributes for the anchor tag.
		 */
		$attr = apply_filters( 'previous_posts_link_attributes', '' );

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