Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress pagination (next_posts_link) on custom wp_query not showing

Similar questions have been asked, but I cannot figure out what I miss!

I have a static page for custom type fields, similar to the regular archive or category page, but I cannot get pagination working.
If I go manually to page 2 (i.e. adding to the link .../page/2) I get the "Newer posts" link, but not on the first page for older ones! next_posts_link() just seems not to exist (no div injected or anything)

Here is my code:

  $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

  $query_args = array (
        'post_type' => 'bb_articoli',
        'meta_key' => 'bb_data-pubblicazione',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
        'posts_per_page' => 2,      //for testing purposes
        'paged' => $paged,
        'meta_query' => array(
            array('key' => 'bb_fonte-pubblicazione',
                  'value' => 2,
                  'compare' => '='
                  )
        )
  );

  $query = new WP_Query($query_args);

    if ( $query->have_posts() ) :
       while ( $query->have_posts()) :
             $query->the_post();
             get_template_part( 'content' , get_post_format());
       endwhile;

     next_posts_link();
     previous_posts_link();

     else :
         get_template_part( 'content', 'none' );
 endif;

Any help is greatly appreciated. Thanks
B

Just for info: using child theme on twenty twelve

like image 717
blu bla Avatar asked Nov 27 '22 17:11

blu bla


1 Answers

The reason why your solution works is because you are overwriting the global $wp_query variable. A better solution would be adding $query->max_num_pages to next_posts_link().

next_posts_link('« Older Entries', $query->max_num_pages)

Where $query is the name of your newly created object. This way you preserve $wp_query.

like image 172
David Lok Avatar answered Dec 06 '22 02:12

David Lok