How to: Offsets and Paging 14comments
Reader John writes in:
How does one use paging with an offset? Doing so breaks the navigation controls.
The problem with using an offset in a query is that WordPress ignores any reference to paging. In other words, you can use an offset and paging, but not both together.
This can be solved by tapping into the post_limits filter.
Step 1: Add the ‘my_post_limit’ Function
The my_post_limit function is what the post_limits filter will use to update the standard loop query.
We’ll use the function to use paging and offsets together. This function should be placed in your theme’s functions.php file.
function my_post_limit($limit) { global $paged, $myOffset; if (empty($paged)) { $paged = 1; } $postperpage = intval(get_option('posts_per_page')); $pgstrt = ((intval($paged) -1) * $postperpage) + $myOffset . ', '; $limit = 'LIMIT '.$pgstrt.$postperpage; return $limit; } //end function my_post_limit
Step 2: Add the Filter Reference
<?php add_filter('post_limits', 'my_post_limit'); ?> <div id="recent"> <h3>Recent Articles</h3>
In the above code, I add a filter for post_limits, which will call the my_post_limit function mentioned in Step 1.
Step 3: Start Your Loop
In this loop, we’ll be declaring a global variable called $myOffset. This will be the offset we’d like to have and is used by the my_post_limit function.
<ul> <?php global $myOffset; $myOffset = 1; $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query(); $wp_query->query('offset='.$myOffset.'&showposts=5'.'&paged='.$paged); ?> <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul>
Step 4: Enable Navigation
We’re just adding the standard next/previous links at the end of the loop.
<div class="navigation"> <div class="alignleft"><?php previous_posts_link('« Previous') ?></div> <div class="alignright"><?php next_posts_link('More »') ?></div> </div> </div>
Step 5: Remove the Filter
In this step, we’ll be removing the post_limits filter and assigning the query back to its original value thanks to a temporary placeholder.
<?php $wp_query = null; $wp_query = $temp;?> <?php remove_filter('post_limits', 'my_post_limit'); ?>
Step 6: You’re done!
Using the above code, you should now be able to use offsets and paging together.
Here is a downloadable file of all the code mentioned in this post.
Thank you John for asking such a great question.











