0

I have a custom post type named 'books' and in a static front page I display all the posts of this type. My problem is that I try to make pagination but all the functions that I found on the internet won't work. Here is my code and the functions like prev_next_posts_link() won't work. What am I doing wrong?

    $paged = ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1;
    $args = array(
        'post_type' => 'books',
        'posts_per_page' => 8,
        'paged' => $paged
    );
    $loop = new WP_Query( $args );?>

    while ( $loop->have_posts() ) : $loop->the_post();
            // some code
    endwhile; ?>


            <?php if ($loop->max_num_pages > 1) {  var_dump($loop->max_num_pages);?>

                <nav class="prev-next-posts">
                    <div class="prev-posts-link">
                        <?php echo get_next_posts_link( 'Older Entries', $loop->max_num_pages ); // display older posts link ?>
                    </div>
                    <div class="next-posts-link">
                        <?php echo get_previous_posts_link( 'Newer Entries' ); // display newer posts link ?>
                    </div>
                    <div>
                        <?php the_posts_pagination(array(
                                'mid_size' => 2,
                                'prev_text' => __( 'Back', 'textdomain' ),
                                'next_text' => __( 'Onward', 'textdomain' ),
                            )); ?>
                        </div>
                </nav>
  • 1
    Please filter pre_get_posts, do not create a new query. Then your pagination will just work. Use our site search to find plenty of examples for that. – fuxia Nov 8 '16 at 15:51
0

Don't create a new query. You can use pre_get_posts for this type of works.

Example : If you want to add books and movies custom post type to home page main loop,

function books_movies_cpt_in_home($query) {
  if ($query->is_home() && $query->is_main_query()) {
    $query->set('post_type', array('books','movies'));
  }
}

add_action('pre_get_posts', 'books_movies_cpt_in_home');
  • Now I don't get the page not found error, but when I change the page the posts displayed are the same. – Madalina Ionescu Nov 9 '16 at 11:34

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.