pagination on custom post wp_query

前端 未结 4 1819
轻奢々
轻奢々 2020-12-01 14:40


        
4条回答
  •  渐次进展
    2020-12-01 15:19

    There are 3 ways that I would suggest for pagination with a custom post wp_query. Unfortunately to this day there isn't a lot of good information about this out there, or at least what is out there is unclear in some cases. Hopefully this helps!

    Note, you also did have the wp_reset_postdata() in the wrong place, but even still more is needed to get it to work correctly.

    Option 1 - use max_num_pages variable

     1, 
            'paged' => $paged, 
            'post_type' => 'cpt_type'
        );
        $cpt_query = new WP_Query($args);
    ?>
    
    have_posts()) : while ($cpt_query->have_posts()) : $cpt_query->the_post(); ?>
    
        //Loop Code Here...
    
    
    
    
    

    You'll see above, a slightly different format for previous_posts_link and next_posts_link which now access the max_num_pages variable. Be sure to use your own query variable name when accessing max_num_pages. Notice I use $cpt_query since that is the variable for my query example.

    Option 2 - temporarily use the $wp_query variable for your loop query

    This is what a lot of folks recommend, but be careful to asign the $wp_query variable to a temp variable and re-assign it or you will run in to all kinds of troubles. Which is why I recommend Option #1. As noted on CSS Tricks, you can do something like this:

    query('showposts=6&post_type=news'.'&paged='.$paged); 
    
      while ($wp_query->have_posts()) : $wp_query->the_post(); 
    ?>
    
      
    
    
    
    
    
    
    

    Option 3 - use WP-pagenavi plugin

    Just as another option what you can do instead is use the WP-pagenavi plugin, and setup your query as in Option #1. But make one change in the code, remove everything within the element and replace with this function, once you have installed the plugin. So you'll end with:

    
    

提交回复
热议问题