Search code examples
wordpresspagination

Next and previous post link in Wordpress?


I want add next post and previous post link my each post. I already do it. But I want when last post that time next post link will hide and first post time previous post will be hide

Below my code is working...

 <?php
     $prev_post = get_previous_post();
     if (!empty( $prev_post )): ?>
      <a href="<?php echo get_permalink( $prev_post->ID ); ?>" title="<?php echo $prev_post->post_title; ?>" class="prev-post">
      <span class="left_arrow"></span> <?php _e("Previous Post", "twentytwelve"); ?></a>
    <?php endif; ?>
      
     
    <?php
    $next_post = get_next_post();
    if (!empty( $next_post )): ?>
    <a href="<?php echo get_permalink( $next_post->ID ); ?>" title="<?php echo $next_post->post_title; ?>" class="next-post">
    <?php _e("Next Post", "twentytwelve"); ?>&nbsp; <span class="right_arrow"></span></a>
    <?php endif; ?>

Below one suppose to work to but not.

<?php if($show_prevnext_post == 1) { ?>
    
    <?php
     $prev_post = get_previous_post();
     if (!empty( $prev_post )): ?>
      <a href="<?php echo get_permalink( $prev_post->ID ); ?>" title="<?php echo $prev_post->post_title; ?>" class="prev-post">
      <span class="left_arrow"></span> <?php _e("Previous Post", "twentytwelve"); ?></a>
    <?php endif; ?>
      
    
    
    <?php
    $next_post = get_next_post();
    if (!empty( $next_post )): ?>
    <a href="<?php echo get_permalink( $next_post->ID ); ?>" title="<?php echo $next_post->post_title; ?>" class="next-post">
    <?php _e("Next Post", "twentytwelve"); ?>&nbsp; <span class="right_arrow"></span></a>
    <?php endif; ?>
    
    
    <?php } ?>

I don't understan why this is not working. Should I need to anything in function.php


Solution

  • Take a look at WordPress's previous_post_link() and next_post_link() functions. They will only output a link if there's a prev/next post. But it will only work if you use them in the WordPress Post Loop

    Hope that helps :-)