How make get_next_post() return first post when viewing last one

Firts / last post make sense if we have an order to refer to. get_next_post() function use post date to decide which post is the next. It optionally use also taxonomy, but once you use the function without any argument, only date is relevant, so the first post is the most recent post in same post type.

To get the most recent post you can use a new WP_Query, get_posts or wp_get_recent_posts.

Example using the latter:

<?php
$next_post = get_next_post();
if ( empty( $next_post ) ) {
  global $post;
  $args = array(
    'numberposts' => 1, 'post_type' => $post->post_type, 'post_status' => 'publish'
  );
  $recent = wp_get_recent_posts( $args, OBJECT );
  $next_post = ! empty( $recent ) ? array_shift( $recent ) : FALSE;
}

if ( ! empty( $next_post ) ) :
  // your code goes here
endif;

Leave a Comment