Using WordPress ‘get_previous_posts_link()’ PHP function

The get_previous_posts_link() WordPress PHP function retrieves the previous posts page link.

Usage

get_previous_posts_link($label);

Example:

echo get_previous_posts_link('Prev');

Parameters

  • $label (string) – Optional. Previous page link text. Default: null

More information

See WordPress Developer Resources: get_previous_posts_link()

Examples

Basic Usage

Display the previous posts page link with default text:

if (get_previous_posts_link()) {
    echo get_previous_posts_link();
}

Custom Label

Display the previous posts page link with custom text:

if (get_previous_posts_link()) {
    echo get_previous_posts_link('Go to previous page');
}

Add a CSS class to style the previous posts page link:

if (get_previous_posts_link()) {
    echo '<div class="nav-previous">';
    echo get_previous_posts_link('Previous Page');
    echo '</div>';
}

Display both the previous and next posts page links:

if (get_previous_posts_link() || get_next_posts_link()) {
    echo '<nav class="pagination">';
    if (get_previous_posts_link()) {
        echo get_previous_posts_link('Prev');
    }
    if (get_next_posts_link()) {
        echo get_next_posts_link('Next');
    }
    echo '</nav>';
}

Remove Trailing Slashes

Remove trailing slashes from generated links if you are using no-end-trailing slashes for your URLs. Add the following filter in your functions file:

add_filter('get_pagenum_link', 'user_trailingslashit');