Search code examples
phpwordpressposts

displaying wordpress recent posts on a template page with previous and next controls


I'm using a wp-query to display on a template page the 5 most recent posts. it works fine, I want also to add previous and next button to navigate to the previous 5 posts, and so on.

I set 'showposts=5', it displays the 5 most recents post, that's perfect, but when clicking on "previous", it redirect me to /page/2/, but the 5 same posts are displayed...

here is my code :

<?php
    $temp = $wp_query; $wp_query= null;
    $wp_query = new WP_Query(); $wp_query->query('showposts=5' . '&paged='.$paged);
    while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

      <h2><a href="<?php the_permalink() ?>"><?php the_time('y-m-d'); ?> | <?php the_title(); ?></a></h2>
<?php endwhile; ?>

    <?php if ($paged > 1) { ?>

    <nav id="nav-posts">
      <div class="prev"><?php next_posts_link('PREVIOUS POSTS'); ?></div>
      <div class="next"><?php previous_posts_link('NEXT POSTS'); ?></div>
    </nav>

    <?php } else { ?>

    <nav id="nav-posts">
      <div class="prev"><?php next_posts_link('PREVIOUS POSTS'); ?></div>
    </nav>

    <?php } ?>

    <?php wp_reset_postdata(); ?>

anyone can help me with this ? I don't know where's the problem...

thanks for your help


Solution

  • i think you are not using the $paged variable;

    use $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    before the WP_Query() function