Using WordPress ‘get_boundary_post()’ PHP function

The get_boundary_post() WordPress PHP function retrieves the boundary post, which is either the first or last post by publish date within the constraints specified by $in_same_term or $excluded_terms.

Usage

get_boundary_post( $in_same_term, $excluded_terms, $start, $taxonomy );

Parameters

  • $in_same_term (bool) (Optional) – Whether the returned post should be in the same taxonomy term. Default: false
  • $excluded_terms (int|string) (Optional) – Array or comma-separated list of excluded term IDs. Default: ”
  • $start (bool) (Optional) – Whether to retrieve the first or last post. Default: true
  • $taxonomy (string) (Optional) – Taxonomy, if $in_same_term is true. Default: ‘category’

More information

See WordPress Developer Resources: get_boundary_post()

Examples

Get the first post in the same category

This example retrieves the first post in the same category as the current post.

$first_post = get_boundary_post(true, '', true);
if (!empty($first_post)) {
    echo '<a href="' . get_permalink($first_post->ID) . '">' . $first_post->post_title . '</a>';
}

Get the last post in the same category

This example retrieves the last post in the same category as the current post.

$last_post = get_boundary_post(true, '', false);
if (!empty($last_post)) {
    echo '<a href="' . get_permalink($last_post->ID) . '">' . $last_post->post_title . '</a>';
}

Get the first post excluding a specific category

This example retrieves the first post, excluding posts from a specific category (e.g., category ID 3).

$first_post_excluded = get_boundary_post(false, '3', true);
if (!empty($first_post_excluded)) {
    echo '<a href="' . get_permalink($first_post_excluded->ID) . '">' . $first_post_excluded->post_title . '</a>';
}

Get the last post in the same tag

This example retrieves the last post in the same tag as the current post.

$last_post_same_tag = get_boundary_post(true, '', false, 'post_tag');
if (!empty($last_post_same_tag)) {
    echo '<a href="' . get_permalink($last_post_same_tag->ID) . '">' . $last_post_same_tag->post_title . '</a>';
}

Get the first post in the same custom taxonomy

This example retrieves the first post in the same custom taxonomy (e.g., ‘product_cat’) as the current post.

$first_post_custom_taxonomy = get_boundary_post(true, '', true, 'product_cat');
if (!empty($first_post_custom_taxonomy)) {
    echo '<a href="' . get_permalink($first_post_custom_taxonomy->ID) . '">' . $first_post_custom_taxonomy->post_title . '</a>';
}