The next_posts_link() works only with original $wp_query

I’ve got custom template that I want to display paged blog posts. This is the beginning of my file:

$wp_query = new WP_Query($args);
        while($wp_query->have_posts()){ $wp_query->the_post();
    <?php next_posts_link('Older Entries'); ?>
    <?php previous_posts_link('Newer Entries'); ?>

It works fine – it displays OLDER and NEWER links when it should. On the first page it will display only a link to older entires. On the second page both to newer entries and yet older ones etc.

But I don’t want to overwrite current $wp_query… I want to use let’s say $wp_query2 for this loop. And the links don’t appear at all if I do this.

According to this: they print a link to the prev/next set of posts within the current query. I assume that $wp_query2 isn’t my “CURRENT QUERY” but $wp_query always is. Can I change that somehow?

Adding &paged=2 manually to the link causes it to correctly go to the next set of posts (next page) and on second, third etc. page previous_posts_link() works even if I use $wp_query2. So, I’m just missing next_posts_link() functionality on every page.

Solutions Collecting From Web of "The next_posts_link() works only with original $wp_query"

next_posts_link and previous_posts_link use the global $wp_query.

function get_next_posts_link( $label = null, $max_page = 0 ) {
    global $paged, $wp_query;

That means you need to do something like this to get those to work correctly.

$orig_query = $wp_query;
$wp_query = new WP_Query($args);
// the rest of your code
$wp_query = $orig_query;

If you are done with $wp_query for that page load there is no reason to preserve it. It should be pretty easy to copy those core functions, modify them to accept a query parameter and create your own paging functions.

Looking at the wordpress source, it looks like next_posts_link uses the global var $paged. My guess is that is only going to work for the primary loop.

A pretty good solution on how to make pagination work for secondary loops is here:

It involves setting the paged query var explicitly in the query, like this:

<h3>Recent Articles</h3>
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();

Hope that helps.