Getting “Newer Posts” and “Older Posts” links on a Specialized Page Template

I am using a Specialized Page Template to display list of posts. I am using the following code for that:

<?php 
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
    'paged' => $paged
);
$all_posts = get_posts($args); 
?>

<?php foreach ( $all_posts as $post ) : setup_postdata( $post );  ?>
/* the loop */
<?php endforeach; ?>

Now I want to put “Newer Posts” and “Older Posts” links below it. next_posts_link() and previous_posts_link() prints nothing here. How can I add these two links on this page?

Related posts

Leave a Reply

3 comments

  1. As from the codex

    next_posts_link() and previous_posts_link() doesn’t work in the custom page template as a static page

    Refer codex for more details

    These functions does not work with static pages

  2. You can simulate it using WP_Query, as it contains the max_num_pages attribute. If $paged is equal to 1, we don’t print the previous link. If it is equal to max_num_pages, we don’t print the next link.

    The links are constructed based on get_the_permalink() that we grab before doing the loop. You have to adjust to your permalinks structure, check the code comments.

    $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
    $this_page = get_permalink();
    $previous = $paged - 1;
    $next = $paged + 1;
    
    $args = array(
        'posts_per_page' => 5,
        'paged' => $paged
    );
    $the_query = new WP_Query( $args );
    
    if ( $the_query->have_posts() ) :
        while ( $the_query->have_posts() ) : 
            $the_query->the_post(); 
            echo '<h2>' . get_the_title() . '</h2>'; 
        endwhile;
    
        if( $paged != 1 ) 
        {
            // DEFAULT PERMALINKS
            # echo "<a href='$this_page&paged=$previous'>previous</a>";
            // PRETTY PERMALINKS
            echo "<a href='{$this_page}page/$previous/'>previous</a>";
        }
    
        if( $paged != 1 && $paged != $the_query->max_num_pages ) 
        {   
            // SEPARATOR
            echo ' | ';
        }
    
        if( $paged != $the_query->max_num_pages ) 
        {
            // DEFAULT PERMALINKS
            # echo "<a href='$this_page&paged=$next'>next</a>";
            // PRETTY PERMALINKS
            echo "<a href='{$this_page}page/$next/'>next</a>";
        }
    
    endif;
    

    Found this article, Next/Previous Post Navigation Outside of the WordPress Loop, although it didn’t help, I’ll leave here as reference.