Siren Brown
Siren Brown

Reputation: 403

Set Previous and next for the posts in wordpress

<?php
  $args = array( 'numberposts' => '1' );
  $recent_posts = wp_get_recent_posts( $args );
  foreach( $recent_posts as $recent ){
    echo '<h1><a href="' . get_permalink($recent["ID"]) .'">' .$recent["post_title"].'</a> </h1> ';
  }
?>

I added this code for getting just single latest post on desired page.

How can I add next and previous button of posts to it?

Upvotes: 0

Views: 114

Answers (2)

Siren Brown
Siren Brown

Reputation: 403

             $previous=$recent["ID"]-1;
             echo '<a href="' . get_permalink($previous) . '">' .   PREVIOUS.'</a> '; 

             $next=$recent["ID"]+1;
             echo '<a href="' . get_permalink($next) . '">' .   NEXT.'</a> ';

I did this and it worked :)

Upvotes: 0

Hardik Solanki
Hardik Solanki

Reputation: 3195

If you want to get previous post link, You can do it using following code:

<?php $prev_post = get_adjacent_post( false, '', true ); ?>
 <?php if ( is_a( $prev_post, 'WP_Post' ) ) { ?>
    <a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_title( $prev_post->ID ); ?></a>
 <?php } ?>

If you want to get next post link, Than:

<?php $next_post = get_adjacent_post( false, '', false ); ?>
 <?php if ( is_a( $next_post, 'WP_Post' ) ) {  ?>
    <a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo get_the_title( $next_post->ID ); ?></a>
 <?php } ?>

You can check more information about this function here : get_adjacent_post()

Upvotes: 1

Related Questions