query_posts and pagination, still stuck after much research

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('&laquo; Previous Story') ?></div>
    <div style="float:right; font-weight:bold"><?php previous_posts_link('Next Story &raquo;') ?></div>

</div>

I’ve got the ‘paged’ value and the post navigation, any idea what’s up now….?

Read More

Thanks 🙂

Related posts

Leave a Reply

3 comments

  1. 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 with query_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 your query_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 using pre_get_posts.

  2. Try this…

    <?php
      global $paged; global $wp_query;
      $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query();
      $wp_query->query('showposts=XX&post_type=POST_TYPE_NAME'.'&paged='.$paged);
      while ($wp_query->have_posts()) : $wp_query->the_post(); 
    ?>
    
        // do your content output here...
    
    <?php endwhile; ?>
    
       // do pagination here...
    
    <?php $wp_query = null; $wp_query = $temp;?>
    
  3. 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.