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
  • 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
    Commented Nov 8, 2016 at 15:51

1 Answer 1

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');
1
  • Now I don't get the page not found error, but when I change the page the posts displayed are the same. Commented Nov 9, 2016 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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