Support » Fixing WordPress » Pagination either not working or showing wrong number of pages

  • I have this category template file and inside of it I could only get this to work although it seems as if its counting wrong:

    $query = new WP_Query( array('cat'=>5,'posts_per_page' => 4,'paged' => get_query_var('paged') ));

    <?php if (  $wp_query->max_num_pages > 1 ) : ?>
            <div id="nav-below" class="navigation">
                <div class="nav-previous"><?php next_posts_link( '<span class="meta-nav"></span> <span class="pagi-bracket">[</span>Older<span class="pagi-bracket">]</span>' ); ?></div>
                <div class="nav-next"><?php previous_posts_link( '<span class="pagi-bracket">[</span>Newer<span class="pagi-bracket">]</span> <span class="meta-nav"></span>' ); ?></div>
            </div><!-- #nav-below -->
    <?php endif; ?>

    Because the pagination will show 7 pages, which is correct if i was showing 10 posts per page, but I am showing 4. I have spent days trying to solve this, have tried so much code and in the end this is the only thing that I could get working although not properly.

    Edit, I found this code which “works”

    function custom_posts_per_page( $query ) {
        if ( is_category( 110 ) && is_main_query() )
    add_action( 'pre_get_posts', 'custom_posts_per_page' );

    But it also changes how many items all of my sidebar widget display. Though pagination works but it is not an acceptable solution if it will affect the sidebar too.

Viewing 1 replies (of 1 total)
  • The problem is that previous/next_posts_link() functions work with $wp_query, not with your WP_Query.

    I think you can get around this by saving a copy of your query before calling the link functions, and restoring it afterward. Something like this:

    <?php $hold_query = clone $wp_query;  // Save original query
    $wp_query = clone $query; ?>
    <div class="navigation">
       <div class="alignleft"><?php next_posts_link('&laquo; Older Entries') ?></div>
       <div class="alignright"><?php previous_posts_link('Newer Entries &raquo;') ?></div>
    <?php $wp_query = clone $hold_query; // Restore original query ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Pagination either not working or showing wrong number of pages’ is closed to new replies.