Next/Prev posts on same page

Hello WordPress Users,

I’m stuck with a problem building my wordpress website and I can’t figure out what to do about it.

Read More

Currently I’m showing 2 posts form the category ‘News’ at the page ‘News’. At the bottom of this page I want a Prev/Next button that shows the next or previous 2 posts from the same category.

So I was searching how I coud do that.
So I found this code:

previous_posts_link('Newer Entries »')
next_posts_link('« Older Entries');

This displays a link like I was expecting.
But both links are not working (page reload, but same entry’s shown).

I also found this in this codex:

posts_nav_link('∞','Go Forward In Time','Go Back in Time');

Also at ‘Setting’ > ‘Reading’ I had set max posts to 2.

I don’t know how I can handle this.
Is there a way to show the next 2 (or ‘X’) posts from the same categorie when a button ‘Next’ or ‘Prev’ is pressed?

Thanks!

Edit:
This is how I get the posts:

$args_news= array(
        'cat' => 1,
        'posts_per_page' => 2,
        'orderby' => 'post_date',
        'order' => 'DESC'
    );

    query_posts( $args_news );

    if ( have_posts() ) :
        while ( have_posts() ) :
            the_post();

          the_title();
          the_content();

          endwhile;
    endif;

But still no idea how I can make pages of this posts.
Currenty it’s displaying the last 2 posts..

Related posts

Leave a Reply

2 comments

  1. Pass Paged into parameter array of query_posts

    You should set get_query_var( 'paged' ); if you want your query to work with pagination.

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args_news= array(
            'cat' => 1,
            'posts_per_page' => 2,
            'orderby' => 'post_date',
            'order' => 'DESC',
            'numberposts' => -1,
            'paged' => $paged,
        );
    
        query_posts( $args_news );
    if ( have_posts() ) :
            while ( have_posts() ) :
                the_post();
    
              the_title();
              the_content();
    
              endwhile;
        endif;
    

    for more information:https://codex.wordpress.org/Pagination

  2. You both have to use the paged query var for the loop, and the max_num_pages var for the links:

    $news_args = array(
        'cat' => 1,
        'paged' => get_query_var('paged'),
        'posts_per_page' => 1,
        'orderby' => 'post_date',
        'order' => 'DESC',
    );
    
    $news_query = new WP_Query($news_args);
    
    if ($news_query->have_posts()) :
    
        while ($news_query->have_posts()) : $news_query->the_post();
            the_title();
            the_content();
        endwhile;
    
        previous_posts_link('prev', $news_query->max_num_pages);
        echo ' — ';
        next_posts_link('next', $news_query->max_num_pages);
    
    endif;