I need a way to link to the first and the last post (CPT) created.

For example, I’m in the last post and if I click in “next” I should go to the first.

Now i have this

<?php
$next_post = get_next_post();

if ( ! empty( $next_post ) ) : ?>
  <div id="nextpost" >
    <a href="<?php echo get_permalink( $next_post->ID ); ?>">
    <!-- <?php echo get_the_post_thumbnail( $next_post->ID, 'thumbnail' ); ?> -->
    </a>
    <span class="nav-next">
      <?php next_post_link( '%link', __( 'Next project', 'twentyeleven' ) ); ?>
    </span>
  </div>
<?php endif; ?>

I need something like else: go to first post.
I would do the same thing when I’m in the first post and when clicking on “previous” i go to the last.

EDIT:

I found a snippet of code that set the order of the navigation through single-post like the menu_order, so maybe the solution now is different.
Here the code of what I’m talking about

function square_adjacent_post_where($sql) {
  if ( !is_main_query() || !is_singular() )
    return $sql;

  $the_post = get_post( get_the_ID() );
  $patterns = array();
  $patterns[] = '/post_date/';
  $patterns[] = '/\'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\"https://wordpress.stackexchange.com/";
  $replacements = array();
  $replacements[] = 'menu_order';
  $replacements[] = $the_post->menu_order;
  return preg_replace( $patterns, $replacements, $sql );
}
add_filter( 'get_next_post_where', 'square_adjacent_post_where' );
add_filter( 'get_previous_post_where', 'square_adjacent_post_where' );

function square_adjacent_post_sort($sql) {
  if ( !is_main_query() || !is_singular() )
    return $sql;

  $pattern = '/post_date/';
  $replacement="menu_order";
  return preg_replace( $pattern, $replacement, $sql );
}
add_filter( 'get_next_post_sort', 'square_adjacent_post_sort' );
add_filter( 'get_previous_post_sort', 'square_adjacent_post_sort' );

2 Answers
2

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 Reply

Your email address will not be published. Required fields are marked *