Marcin
Marcin

Reputation: 91

Wordpress pagination wp_query->max_num_pages return 0

I have problem in pagination in wordpress custom page. I using template dazzling, this is pagination function: https://github.com/puikinsh/Dazzling/blob/master/inc/template-tags.php But always $GLOBALS['wp_query']->max_num_pages is 0 (null). I try many time to change it, this is what I do now:

 $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
  $query_args = array(
    'post_type' => 'post',
    'category__in' => '4',
    'posts_per_page' => 3,
    'max_num_pages' => 5,
    'paged' => $paged
  );
  // create a new instance of WP_Query
  $the_query = new WP_Query( $query_args );
?>

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); // run the loop ?>
  <article>
    <h1><?php echo the_title(); ?></h1>
    <div class="excerpt">
      <?php the_excerpt(); ?>
    </div>
  </article>
<?php endwhile; ?>

<?php if ($the_query->max_num_pages > 1) { // check if the max number of pages is greater than 1  ?>
<?php dazzling_paging_nav()); ?>

<?php } ?>

<?php else: ?>
  <article>
    <h1>Sorry...</h1>
    <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
  </article>
<?php endif; ?>

What I do wrong? Any idea?

Upvotes: 6

Views: 34989

Answers (3)

Laila
Laila

Reputation: 1511

Not quite sure it can help someone but just in case. I had the same issue ( $wp_query->max_pages_number returning 0) and I got stuck because of something very silly.

I realized that I had this code somewhere else in my theme :

function no_rows_found_function($query)
{ 
  $query->set('no_found_rows', true); 
}

add_action('pre_get_posts', 'no_rows_found_function');

It was be useful to improve the performance of WP_Query but the no_found_rows disables the pagination. Make sure it's not somewhere in a plugin or in your theme :)

Upvotes: 10

Goran Jakovljevic
Goran Jakovljevic

Reputation: 2820

Had the same problem where max_num_pages wouldnt work in page templates, but would work in archive template. The solution for me was a bit of PHP:

  1. Count all published posts
  2. Get posts per page that is set in options
  3. Round it to max.

        $published_posts = wp_count_posts()->publish;
        $posts_per_page = get_option('posts_per_page');
        $page_number_max = ceil($published_posts / $posts_per_page);
    

Upvotes: 6

AI.Takeuchi
AI.Takeuchi

Reputation: 51

global $wp_query;
global $page, $numpages, $multipage, $more;

if( is_singular() ) {
    $page_key = 'page';
    $paged = $page;
    $max = $numpages;
} else {
    $page_key = 'paged';
    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max = $wp_query->max_num_pages;
}

Upvotes: 5

Related Questions