WordPress get_boundary_post() function: Retrieve boundary post by publish date

Tutorial: Using the get_boundary_post Function in WordPress

Learn how to retrieve the adjacent posts in WordPress using get_boundary_post function.

Introduction

When working with WordPress, it’s often necessary to display the adjacent posts or navigate the posts in a loop. WordPress provides a handy function called get_boundary_post that allows you to retrieve the first or last post before or after the current post’s publish date.

Syntax

The get_boundary_post function has the following syntax:

get_boundary_post( bool $in_same_term = false, array|string $excluded_terms = '', bool $start = true, string $taxonomy = 'category' )

Parameters

  • $in_same_term: (Optional) Whether to include only posts from the same category as the current post. Default is false.
  • $excluded_terms: (Optional) Array or comma-separated string of term IDs to exclude. Default is empty.
  • $start: (Optional) Whether to retrieve the first or last post before or after the current post’s publish date. Default is true (retrieve first post).
  • $taxonomy: (Optional) The taxonomy to use for term matching. Default is category.

Return Value

The get_boundary_post function returns an object containing the post data of the adjacent post.

Examples

Example 1: Retrieve the Previous Post

If you want to retrieve the previous post, you can use the get_boundary_post function with the $start parameter set to true:

<?php
$previous_post = get_boundary_post(true);
if ($previous_post) {
  echo '<h4>'.$previous_post->post_title.'</h4>';
  echo '<p>'.$previous_post->post_content.'</p>';
}
?>

Example 2: Retrieve the Next Post in the Same Category

To retrieve the next post in the same category as the current post, you can pass true to the $in_same_term parameter:

<?php
$next_post = get_boundary_post(true, '', false);
if ($next_post) {
  echo '<h4>'.$next_post->post_title.'</h4>';
  echo '<p>'.$next_post->post_content.'</p>';
}
?>

Example 3: Retrieve the Last Post

If you need to retrieve the last post, set the $start parameter to false:

<?php
$last_post = get_boundary_post(false);
if ($last_post) {
  echo '<h4>'.$last_post->post_title.'</h4>';
  echo '<p>'.$last_post->post_content.'</p>';
}
?>

Conclusion

Using the get_boundary_post function allows you to easily retrieve the adjacent posts in WordPress, whether you need to display the previous, next, first, or last post. You can customize the function parameters to suit your specific needs and enhance the navigation experience on your WordPress website.