简体   繁体   中英

wordpress WP_QUERY custom post type pagination not working

i'am trying to display pagination on a category.php page, whith this code :

      $cat = wp_strip_all_tags( get_the_category_list());
      global $wp_query;

     $paged = 1;  
    if ( get_query_var('paged') ) $paged = get_query_var('paged');  
    if ( get_query_var('page') ) $paged = get_query_var('page');

    $temp = $wp_query; 
            $wp_query = null; 


      echo $paged;

      ?> 
  <?php $wp_query = new WP_Query( array(
      'paged'     =>$paged,
      'posts_per_page'=>1,
      'post_type'   => 'post',
      'category_name' => $cat,



    )); ?>

  <?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

     // do something

     <?php endwhile; ?>

     <?php if ($wp_query->max_num_pages > 1) {  ?>
     <?php echo $wp_query->max_num_pages; ?>
        <nav class="prev-next-posts">
          <div class="prev-posts-link">
            <?php echo get_next_posts_link( 'Older Entries', $wp_query-    >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>
        </nav>
     <?php } ?>

the pagination does not work (when i click on "Older posts" i get redirected to the home page), but when i force the $paged variable like this $paged = 2; ...... it show the second page as expected ! Can someone help me !

get_next_posts_link() usually points to older entries (toward the end of the set) and get_previous_posts_link() usually points to newer entries (toward the beginning of the set).

Example:

$cat = wp_strip_all_tags( get_the_category_list());

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

$the_query = new WP_Query( array( 
    'post_type' => ‘post’,
    'orderby' => 'date',
    'category_name' => $cat,
    'order' => 'DESC',
    'paged' => $paged,
    'posts_per_page' => 2) 
);

//usage of the $the_query
while ( $the_query->have_posts() ) : $the_query->the_post();

// Do Something

endwhile; 

//pagination
get_next_posts_link('Older', $the_query->max_num_pages);
get_previous_posts_link( 'Newer', $the_query->max_num_pages);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM