Wordpress post pagination continuous

I have these shortcodes which I am using as links in my front end to get the next post and previous post.

When I get to the last post it just keeps reloading the last post again. How can I get it to loop back to the first post?

function prev_shortcode($atts) {
    $prev_post = get_previous_post();
    $permalink = get_permalink($prev_post);
    return ($permalink);
}
add_shortcode( 'prev', 'prev_shortcode' );

function next_shortcode($atts) {
    $next_post = get_next_post();
    $permalink = get_permalink($next_post);
    return ($permalink);
}
add_shortcode( 'next', 'next_shortcode' );

Topic next-post-link previous-post-link shortcode pagination Wordpress

Category Web


get_next_post returns null if there is no post anymore. And then get_permalink will have a null value for $next_post, so it will get the permalink for the current post, resulting in linking to the same post again and again.

You should thus check for null, and if so, link to the first (latest) post. Something along the lines of (in your code style):

function next_shortcode( $atts ) {
    $next_post = get_next_post();
    if ( ! is_null($next_post) ) {
        return get_permalink( $next_post );
    }
    $posts = get_posts( 'numberposts=1' );
    return $posts[0];
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.