Quick Tip: Pre Get Posts

Quick Tip: Pre Get Posts

Written on: 04/06/2016

On many occasions, I find the need to create a custom post type, and on top of that, I don’t just want to display 10 posts in the archive. So, with a bit of ‘pre get posts’ magic, we can set the number of posts to display, just like you would with a normal WP Query. See the code below:


function set_posts_per_page_for_cpt( $query ) {
if ( !is_admin() && $query->is_main_query() && is_post_type_archive( 'books' ) ) {
$query->set( 'posts_per_page', '-1' );
}
}
add_action( 'pre_get_posts', 'set_posts_per_page_for_cpt' );

What we’re doing here is going into our theme functions file and setting up a new function. Then within that we check that we’re not in the admin area {!is_admin()} and then we also do a double check to make sure we’re in the main query {$query->is_main_query()} and finally that we’re in our custom post type, which in this instance is for ‘books’ {is_post_type_archive( ‘books’ )}.

Once we check those things, we use {$query->set} and run a simple parameter through it, in real talk, saying Post to show on the page = unlimited (don’t forget that -1 means unlimited in WordPress when referring to how many posts to show).

Finally, we add the function to the pre_get_posts action and voila!

Full reference: Read the WordPress Codex

Let's work together on your project.

Have I made an impression?

If so, then why not take the next step, which is a totally free indicative quote calculator. My hand coded algorithm asks you a few simple questions, and then will be able to give you a ballpark figure that we can use as a jumping off point for your project. Get a free quote now