0

I have created a custom post type named lesson, and I want to display all lessons, so I created a custom page named lesson.php, inside, I added a query to look for all the posts which type are lesson.

<?php
$page = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1;
$query = new WP_Query( array( 'post_type' => 'lesson', 'paged' => $page ) );

while ($query->have_posts()) : $query->the_post(); ?>
  <div class="lesson">
    <h1><?php echo the_title(); ?></h1>

    <p><?php echo the_content(); ?></p>
  </div>
<?php endwhile; // end of the loop. 
wp_reset_query(); ?>

<div class="nav-previous alignleft"><?php next_posts_link( 'Next Lessons', $query->max_num_pages ); ?></div>
<div class="nav-next alignright"><?php previous_posts_link( 'Previous Lessons' ); ?></div>

It works, the problem is pagination, the next_post_link always shows up, even in the last page, linking to the same page, that itself is not a very big problem, the biggest issue is previous_posts_link just returns null, and nothing is displayed.

Reading about this issue on the internet I found out the query must be named $wp_query as it's a global object those functions use, nevertheless when I change the name of the query it still doesn't work.

  • When you created the custom post type, did you set pagination to true? It's one of the arguments you pass during the post type registration. – gdaniel Mar 2 '14 at 1:46
  • I tried adding that argument, still doesn't work – gosukiwi Mar 2 '14 at 2:23
  • those functions are intended for use on archive pages, you're using it on a single page. you can instead have WordPress generate your archive by setting has_archive to true when you register your post type, then you won't need a page with a custom query, and pagination will work. – Milo Mar 2 '14 at 2:47
  • Interesting, I created a custom pagination function, but that solution is just better :) Thanks! – gosukiwi Mar 2 '14 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.