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

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

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