Pagination in a Custom Query

The Genesis pagination uses standard WordPress pagination functions, like previous_post_link() and next_post_link(). These functions only apply to the main WordPress query, not any custom ones. So if you created a page template that had a custom query in it, the main query would be for that page’s content. If you tried adding pagination after your custom query, none would show up since the page isn’t paginated.

The solution is to make your custom query override the global $wp_query variable, which tricks the WordPress functions into thinking it is the main query. Then, once you’re done with pagination, add wp_reset_query() to set the query back to how it should be.

view raw template-gallery.php hosted with ❤ by GitHub

1. Remove the default pagination: remove_action( 'genesis_after_endwhile', 'genesis_posts_nav' );
2. Build your custom loop $args, and include 'paged' => get_query_var( 'paged' )
3. Overwrite $wp_query with your new one. So instead of $loop = new WP_Query( $args );, you use global $wp_query; $wp_query = new WP_Query( $args );. Since all the conditional tags like is_singular() are really a wrapper for $wp_query->is_singular(), this changes all conditional tags to be based off of your custom query.
4. After your endwhile, place genesis_posts_nav();. This will render the navigation you have set in Genesis > Theme Settings
5. After your endif; place wp_reset_query();. This will revert $wp_query and $post to the original query.

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk