Posts archive index pagination in a static page custom query

In WordPress, I have a page for News that is using a specific page template I created. This page is populated by news posts assigned to the news category. I need to show only two of the latest news posts on this page with Previous / Next links at the bottom if users want to read more news. However, the next / previous links are not working. Clicking on them does go to /page/2 but it’s shows the same posts. Here is my code .. any ideas / help appreciated!

<div id="primary">
<div id="content" role="main">
            <div id="news">
    <?php query_posts( "category_name=news&orderby=date&order=ASC&posts_per_page=2" ); ?>
                <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
                    <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
                    <p class="post-date">Posted on <?php the_date(); ?>
                    <?php the_excerpt(); ?>
                <?php endwhile; ?>
                <?php endif; ?>

                <div id="more-posts">
                    <div class="previous-link"><?php previous_posts_link("< previous news") ?></div><div class="next-link"><?php next_posts_link ("more news >") ?></div>
                </div>
             </div>
    </div><!-- #content -->
    </div><!-- #primary -->

Related posts

Leave a Reply

1 comment

  1. When you perform a custom query such as this one, you have to do a bit of a “hack” to get pagination to work properly.

    Change this:

    <?php 
    query_posts( "category_name=news&orderby=date&order=ASC&posts_per_page=2" ); 
    ?>
    

    …to a WP_Query call:

    <?php 
    $news_query = new WP_Query( "category_name=news&orderby=date&order=ASC&posts_per_page=2" ); 
    ?>
    

    And then you need to *move your custom query object into the $wp_query global`:

    // Move $wp_query into a temp holder
    $temp = $wp_query;
    // Nullify the global object
    $wp_query = null;
    // Now move your custom query into the 
    $wp_query = $news_query;
    

    Then, update your loop initiation, from this:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    

    …to this:

    <?php if ( $news_query->have_posts() ) : while ( $news_query->have_posts() ) : $news_query->the_post(); ?>
    

    This should cause the pagination to work as expected.

    When you close your loop:

    <?php endwhile; ?>
    <?php endif; ?>
    

    …just restore the original $wp_query global:

    <?php endwhile; ?>
    <?php endif; ?>
    <?php $wp_query = $temp; ?>
    

    And you should be good to go.