Why get_next_post_link() or get_previous_post_link() doesn’t return the required links?

It is in WordPress, Divi.
It seemed to me a simple task but somehow I haven’t managed to get the proper result spending tons of hours with coding and testing.
Currently I’m working on a website, where there are posts and I intend to give the possibility the user to jump to the adjacent posts with a simple link pointing to them.
I’ve tried to put them in functions.php, then in single.php but the same result…
Nothing.
I checked it via WordPress debug.log, it shows that the functions return no value at all. Note that I mention debug.log, because I forwarded outputs over there.

add_filter( 'the_content', 'post_navigation', 10, 2 );
function post_navigation($content) {
    $post = get_post();
    $post_type = get_post_type( $post );

    if ( $post_type == 'post' ) {
        $next_p = get_previous_posts_link();
        $content = $content . $next_p;

        return $content;
    } else {
        return $content;    
    }

}

It has no proper formatted output, but first I just wanted to get any result.
Note: debug.log shows that the the_content hook has been 2 times called at a simple post displaying second times with the content:

You are being timed-out out due to inactivity. Please choose to stay signed in or to logoff.</p>
<p>Otherwise, you will be logged off automatically.</p>

Any help would be highly appriciated!

2 Answers
2

Warning Edit: Mark Kaplun’s answer brings up a very good point – this will modify your content in unexpected ways. Say, for instance, you have another application that reads this post content from the WordPress API – that content will also have these links which is probably not what you want. You should really be applying these methods in your theme templates instead of appending this information to the content itself. You could possibly use sanity checks such as checking against the global $pagenow variable, or other methods, to ensure you only do this operation when you’re viewing a post on the front-end.

It appears you’re using the incorrect methods. WordPress is kind of tricky sometimes, and in this case you want to be using get_previous_post_link instead of get_previous_posts_link (note: the difference is that in the method you are calling, posts is plural – in the method you want, post is singular).

So give these a shot

  • get_previous_post_link – Retrieves the previous post link that is adjacent to the current post.
  • get_next_post_link – Retrieves the next post link that is adjacent to the current post.

EDIT: Here is an updated example based on your code

add_filter( 'the_content', 'post_navigation', 10, 2 );

function post_navigation($content) {
    $post = get_post();

    if ( 'post' === $post->post_type ) {
        $next_p  = get_next_post_link();
        $prev_p  = get_previous_post_link();
        $content = "{$content}<br/>{$prev_p} | {$next_p}";
    }

    return $content;    
}

Leave a Comment