Check if next post is available and output a link

I’m checking if the next post is available in the same category. If it is, output the link. If it’s not, output a static text. I have created a function for this:

function thelink() {
    $next_link = next_post_link('%link', 'Next →', TRUE);
    if($next_link){
        echo $next_link;
    } else{
        echo 'Next →';
    }
}

Then, I list it as follows:

Read More
echo '<ul>';
echo '<li>';
thelink();
echo '</li>';
echo '</ul>';

The problem is, the output includes both the link AND the static text. It does check for the posts though. Here’s what happens:

If this is NOT the last post, the output is as following, rendering the Next twice. Once with the link, followed by static text:

<li><a href="urlofthenextpage" rel="next">Next →</a>Next →</li>

If this is the last post, the output is just static text:

<li>Next →</li>

I realize that the problem seems to be in the loop. But I’m out of ideas on how to get this working. Help is VERY much appreciated.

Related posts

Leave a Reply

1 comment

  1. The problem is that next_post_link actually prints the link.

    If you want to do this as described above, you could use output buffering:

    function thelink() {
        ob_start();
        next_post_link('%link', 'Next &rarr;', TRUE);
        $next_link = ob_get_clean();
        if ($next_link) echo $next_link;
        else echo 'Next &rarr;';
    }