0

This question already has an answer here:

I thought I know how to add pagination to a custom loop and I've seen these questions and tutorials:

but for some reason it doesn't work at this time. I created myfile.php, named it to "My Page Template" and set that to be my front page in Admin Panel > Settings > Reading.

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

$args = array(
    'post_type' => array('my_custom_post_type'),
    'paged' => $paged,
    'posts_per_page' => 3,
    'ignore_sticky_posts' => 1
);

$wp_query = new WP_Query( $args );
var_dump($wp_query);
if($wp_query->have_posts()) :
    while($wp_query->have_posts()) : $wp_query->the_post();
        // show post
    endwhile;
endif;

next_posts_link('Next posts');

wp_reset_query();
wp_reset_postdata();

What happens:

  • Front page shows 3 posts as expected.
  • "Next posts" link is shown and points to http://example.com/page/2/ as expected.
  • While I'm on http://example.com/page/2/ it shows the same set of posts and "Next posts" link points to http://example.com/page/2/ which is not what I want.
  • var_dump($wp_query) shows public 'max_num_pages' => float 8.
  • var_dump($wp_query) shows public 'found_posts' => string '24' (length=2).
  • var_dump($wp_query) shows public 'is_paged' => boolean false.
  • var_dump($wp_query) shows 'paged' => int 1 (when I'm on page number 2).
  • When I'm renaming $wp_query to $my_custom_query then "Next posts" link doesn't show at all.

Is there anything else I should do here?

UPDATE: I managed to set proper $paged by changing $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; to $paged = (get_query_var('page')) ? get_query_var('page') : 1; but it still shows a wrong navigation link.

marked as duplicate by Chip Bennett, fuxia Oct 29 '13 at 22:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • After you use the code in your update, before next_posts_link try: global $paged; $paged = get_query_var('page');. – gmazzap Sep 8 '13 at 16:34
  • @G.M. It still points to example.com/page/2 when I'm on example.com/page/2. $paged is 2. – Paul Sep 8 '13 at 16:44
  • mmm, I've tested your code, exactly how you have posted, only implementing the change you pointed in your update (without using what I said in previous comment). It worked perfectly. So I think there is something else that cause the issue. – gmazzap Sep 8 '13 at 16:52
  • I forgot to mention that my loop is located in loop.php and I do get_template_part() i myfile.php. It seems not to pass variables there... Adding global $paged; before $paged = (get_query_var('page')) ? get_query_var('page') : 1; and not only before next_posts_link() helped! Thank you for yor help! This is resolved! – Paul Sep 8 '13 at 17:06

Browse other questions tagged or ask your own question.