I’m having trouble adding pagination to a page. I’m using WP_query
and would like to pull back 4 posts per page. The basic query seems to work OK but I must be missing something regarding pagination.
// The query for 4 posts
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query = new WP_Query();
$query->query('showposts=4'.'&paged='.$paged);
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="post">
<a href="https://wordpress.stackexchange.com/questions/160175/<?php the_permalink(); ?>"><?php the_title(); ?></a>
<p class="author">by <?php the_author(); ?></p>
</div>
<?php endwhile; ?>
<!-- end of the loop -->
<nav>
<?php previous_posts_link('« Newer posts') ?>
<?php next_posts_link('Older posts »') ?>
</nav>
<?php wp_reset_postdata();
// If no results appear
else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
I’ve set the var for the pagination at the top as such:
$query->query('showposts=4'.'&paged='.$paged);
Am including the pagination nav as such:
<nav>
<?php previous_posts_link('« Newer posts') ?>
<?php next_posts_link('Older posts »') ?>
</nav>
But I just get empty HTML <nav></nav>
– but no errors, and I can’t work out what I am missing.
Edit: As per the suggestion I have updated as:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 4,
'paged' => $paged,
);
$query = new WP_Query( $args );
and updated the button link to:
<?php next_posts_link( 'Older posts »', $query->max_num_pages ); ?>
I am still not seeing a pagination link.