WordPress pagination is not working when don’t preserve the initial query object

On a custom page template on my custom theme I have the below query. When I do it this way the pagination is working :

 $myqueryname = $wp_query;
 $mypost_args = array( 'post_type' => 'friends', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => 4, 'paged' => $paged);
 $wp_query = new WP_Query($mypost_args);
 while ( $wp_query->have_posts() ) : $wp_query->the_post();

    Some html.....

 endwhile;

 previous_posts_link('Prev');
 next_posts_link('Next');

But when I am using this way the pagination is not working :

Read More
$mypost_args = array( 'post_type' => 'friends', 'orderby' => 'title', 'order' => 'ASC');
$loop = new WP_Query( $mypost_args );
while ( $loop->have_posts() ) : $loop->the_post();
         Some html.....

endwhile;

previous_posts_link('Prev');
next_posts_link('Next');
wp_reset_query();

I was wondering why is this happening ? What is the difference ? Sorry if my question is vague but this will help me to understand better the way wordpress is working and not just copy-paste codes from forums.

Thanks in advanced.

Related posts

Leave a Reply

1 comment

  1. If you look into the code of the get_next_posts_link (function that next_posts_link calls) it has the following code:

    global $paged, $wp_query;
    
    if ( !$max_page )
        $max_page = $wp_query->max_num_pages;
    ...
    

    And this is the usage of next_posts_link

     <?php next_posts_link( $label , $max_pages ); ?> 
    

    It looks to me that when you use custom query you need to specify $max_pages for pagination to work.

    Try modifying your pagination code to this:

    previous_posts_link('Prev', $loop->max_num_pages);
    next_posts_link('Next', $loop->max_num_pages);