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">« Previous Posts</a>
Parameters
$display
(bool) – Optional. Whether to echo the link. Default: true
More information
See WordPress Developer Resources: previous_posts()
Examples
Display Previous Posts Link
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;
Retrieve Previous Posts Link
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;
Customize Previous Posts Link
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);**
Display Previous Posts Link with Custom Text
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;
Display Both Next and Previous Posts Links
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 »'); echo '</div>'; endif;