I’m trying to create a paginated list of posts, and have used the Codex to write some code but I appear to be doing something wrong.

These are my wp_query args

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
            $the_query = new WP_Query(
                array
                    (
                        'posts_per_page' => 5,
                        'post_type' => 'post',
                        'paged' => $paged
                    )
            );

The content of $paged does output as 1 which would be expected

I’ve added next_posts_link to my if statement but they don’t show.

if ( $the_query->have_posts() ) {
                previous_posts_link( '« Newer Entries' );
                while ( $the_query->have_posts() ) {
                    $the_query->the_post();
                    echo '<div class="news-item">';
                        // post stuff here
                    echo '</div>';
                }
                next_posts_link( 'Older Entries »', 0 );
            }

EDIT

The page on which this shows is not a front page, but is a static page I created. I created page-news.php template and then created a page called ‘News’ and that it where this code resides. Could that be the reason?

1 Answer
1

This is working for me on a single page using a template. Just be sure to set next_posts_link( 'Older Entries »', $the_query->max_num_pages );.

// set the "paged" parameter (use 'page' if the query is on a static front page)
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1';
$args = array (
    'nopaging'               => false,
    'paged'                  => $paged,
    'posts_per_page'         => '5',
    'post_type'              => 'post',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {

    previous_posts_link( '« Newer Entries' );

    while ( $query->have_posts() ) {
        $query->the_post();
        echo '<div class="news-item">';
            // post stuff here
                echo '<h1 class="page-title screen-reader-text">' . the_title() . '</h1>';
        echo '</div>';
    }

    next_posts_link( 'Older Entries »', $query->max_num_pages );

} else {
    // no posts found
    echo '<h1 class="page-title screen-reader-text">No Posts Found</h1>';
}

// Restore original Post Data
wp_reset_postdata();
  • https://codex.wordpress.org/Function_Reference/next_posts_link
  • https://codex.wordpress.org/Function_Reference/previous_posts_link
  • https://generatewp.com/wp_query/

Leave a Reply

Your email address will not be published. Required fields are marked *