The more I use custom post types in WordPress, the more I find myself leaving until the last minute (and often forgetting) the issue of pagination. WordPress has paginate_links() and a couple other functions to help make pagination easier, but it’s still kind of a pain, and I ended up rewriting certain common functions (like functions to get the per_page parameter out of the $_GET global, etc) in multiple projects.
So I took a little time to write a reusable class for a lot of these common functions. It’s called – tada! – Boone’s Pagination. This is not so much a plugin in itself (though if you plan to use it a lot on a client site, you can activate it as a plugin) as it is a helper for people building themes and plugins. Here’s how you use it:
<br /> require_once( dirname(__FILE__) . '/boones-pagination.php' ); // You only need this if you don't activate it as a plugin</p> <p>$pagination = new BBG_CPT_Pag;</p> <p>$my_query_args = array(<br /> 'post_type' => 'my_post_type',<br /> 'paged' => $pagination->get_paged,<br /> 'posts_per_page' => $pagination->get_per_page // This does all the work of fetching the pagination arguments out of the $_GET global<br /> );</p> <p>$my_query = new WP_Query( $my_query_args );<br /> $pagination->setup_query( $my_query ); // Now that you've run the query, finish populating the object</p> <p>if ( $my_query->have_posts() ) :<br /> while ( $my_query->have_posts() ); $my_query->the_post();<br /> the_title(); // Do whatever you'd normally do in The Loop<br /> endif;</p> <p>$pagination->currently_viewing_text(); // eg "Viewing 11-20 of 34"<br /> $pagination->paginate_links(); // These are the links themselves<br />
I’ll keep adding handy functions to the class as I think of them, but you should feel free to extend it yourself. I’ve also added plenty of inline docs, so crack open the source to learn more about it. Follow Boone’s Pagination on Github.