I need to paginate some custom posts…I canât see why but Iâm getting 404âs when going to the next page. Hereâs my code:
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array( 'post_type' => 's_stories', 'posts_per_page' => 4 , 'paged'=>$paged) );
if (have_posts()){
while (have_posts()) { the_post(); ?>
<div class="post">
<h2 class="title"><a href="<?php echo get_permalink($post->ID); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
</div> <!-- end post -->
<div class="clear"></div>
<?php } } ?>
<div class="paging">
<div style="float:left; font-weight:bold"><?php next_posts_link('« Previous Story') ?></div>
<div style="float:right; font-weight:bold"><?php previous_posts_link('Next Story »') ?></div>
</div>
Iâve got the âpagedâ value and the post navigation, any idea whatâs up now….?
Thanks 🙂
Don’t use
query_posts
. This is a classic example of what happens when you do 🙂Basically, when WordPress receives an url, it interprets this as a query – it then queries the database to find the results (if any) and serves up an appropriate template (such as 404.php in the case of no results).
If it happens to reach your template page – it’s then told to discard that query, and start a new one (which is wasteful) and will break pagination.
Basically pagination adds the
paged
query variable to the current url – this new url (which should take you to page 2, say) – forms the basis of the query to recieve page 2 – but the url in the address bar isn’t the content you are after (because you discard that and start a new query withquery_posts
. The end result is that a query, that you don’t really want, is performed and turns up no results, so the 404 template is served and the template with yourquery_posts
is never reached.Have a look at the above linked post for alternatives to
query_post
, but as this is the ‘main query’ (the query based on the recieved url) you want to be usingpre_get_posts
.Try this…
query_posts()
should not be used in general and especially if you are trying to mess with pagination.Both pagination and 404 logic happens before template file (and
query_posts()
in it) even starts to load.To tweak main query of the page one of the best options is to use
pre_get_posts
hook.