WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Custom Next/Previous links on posts (3 posts)

  1. creativeworldstudio
    Member
    Posted 5 years ago #

    Hello -

    I have a small problem with some custom next/previous post links I'm using - Here's the code:

    <?php	$next_post = get_next_post();
    	$prev_post = get_previous_post(); ?>
    
    <a href="<?php echo get_permalink($prev_post->ID);?>" title="<?php echo str_replace('"', '\'', $prev_post->post_title); ?>" class="">&laquo; Previous post<br /><strong>&quot;<?php echo str_replace('"', '\'', $prev_post->post_title); ?>&quot;</strong></a>
    
    <a href="<?php echo get_permalink($next_post->ID);?>" title="<?php echo str_replace('"', '\'', $next_post->post_title); ?>"  class="">Next post &raquo;<br /><strong>&quot;<?php echo str_replace('"', '\'', $next_post->post_title); ?>&quot;</strong></a>

    The problem is that when you're at the most recent post, the Next Post will link to itself (current/most recent post). How can I hide the "Next Post" link altogether when on the most recent post?

    (note- this also happens on the most Previous post)

  2. creativeworldstudio
    Member
    Posted 5 years ago #

    I think I've managed to solve this myself - using this code:

    <?php
    $prev_post = get_previous_post();
    if($prev_post) {
       $prev_title = strip_tags(str_replace('"', '', $prev_post->post_title));
       echo "\t" . '<a rel="prev" href="' . get_permalink($prev_post->ID) . '" title="' . $prev_title. '" class=" ">&laquo; Previous post<br /><strong>&quot;'. $prev_title . '&quot;</strong></a>' . "\n";
                    }
    
    $next_post = get_next_post();
    if($next_post) {
       $next_title = strip_tags(str_replace('"', '', $next_post->post_title));
       echo "\t" . '<a rel="next" href="' . get_permalink($next_post->ID) . '" title="' . $next_title. '" class=" ">Next post &raquo;<br /><strong>&quot;'. $next_title . '&quot;</strong></a>' . "\n";
                    }
    ?>

    This is working for me currently so I'll mark this post as Solved, but if anyone has a better method, please let me know/make a post here.

    Cheers.

  3. Quiltro
    Member
    Posted 5 years ago #

    Thanks a lot! for this chunk of usefull code. You saved me.

Topic Closed

This topic has been closed to new replies.

About this Topic