Using WordPress ‘previous_posts()’ PHP function

The previous_posts() WordPress PHP function displays or retrieves the previous posts page link.

Usage

previous_posts($display);

Example:

Input:

previous_posts(true);

Output:

<a href="https://example.com/page/2">&laquo; Previous Posts</a>

Parameters

  • $display (bool) – Optional. Whether to echo the link. Default: true

More information

See WordPress Developer Resources: previous_posts()

Examples

This example displays the previous posts link on a blog page.

if (have_posts()) :
    while (have_posts()) : the_post();
        // Display post content
    endwhile;

    **previous_posts(true);**
endif;

This example retrieves the previous posts link and stores it in a variable.

$previous_posts_link = **previous_posts(false)**;

if ($previous_posts_link) :
    echo '<div class="nav-previous">' . $previous_posts_link . '</div>';
endif;

This example customizes the previous posts link text and attributes.

add_filter('previous_posts_link_attributes', 'custom_previous_posts_link_attributes');

function custom_previous_posts_link_attributes() {
    return 'class="btn btn-primary" aria-label="Previous Posts"';
}

**previous_posts(true);**

This example displays the previous posts link with custom text.

$prev_link = get_previous_posts_link('Older Posts');

if ($prev_link) :
    echo '<div class="nav-previous">' . $prev_link . '</div>';
endif;

This example displays both next and previous posts links together.

if (have_posts()) :
    while (have_posts()) : the_post();
        // Display post content
    endwhile;

    echo '<div class="post-navigation">';
    **previous_posts(true);**
    next_posts_link('Next Posts &raquo;');
    echo '</div>';
endif;