If you want to limit or even make UNlimited the number of results produced by the WordPress loop, without starting a new wp_query, I have a solution for you. This will work on an results or archive page, anywhere the loop is used, including results for authors, custom taxonomies, custom post types, or categories.
In this example, we are going to make the number of posts displayed unlimited, though this same method would work to alter the main loop in any way, without discarding the original query. The secret lies in query_posts. Distinct from wp_query, query_posts in meant to alter the existing query while preserving its original parameters. So what we need to do is place this new code right before the loop. The loop typically begins with something like:
1 |
<?php if ( have_posts() ) : ?> |
So right before that is where we place our new code, which is:
1 2 3 4 |
<?php global $query_string; query_posts( $query_string . '&posts_per_page=-1' ); ?> |
Having posts_per_page set to -1 allows us to display an unlimited number of results. We could also add a ‘&’ and then another parameter after “posts_per_page=-1” to further alter our query. The list of parameters that can be used here is quite exhaustive, but you can find a list here: wp_query parameters.
If you wish to use the more traditional and flexible $args array to specify parameters, that would look more like this:
1 2 3 4 |
$args = array( 'posts_per_page' => '-1', ); query_posts( $args ); |
And that’s all there is to it! It’s nice and simple and to the point, hopefully you like it. You can also alter the loop to query future posts fairly easily, for a little extra functionality if you need it. Let me know if you have any questions about it! You can reach me in the comments here, or email me at brian@brianjohnsondesign.com or tweet @brianjonline. Thanks!
6 Comments on “Change Number of Results in Loop: WordPress”
Thank you Brian for this
Thanks a lot, mate! It really worked!
But… I have pagination function from the theme which brakes after the second page. The code uses ‘the_posts_pagination’ function.
Any idea how to fix it?
Thank you,
Vasil
Unfortunately there are many things that could go wrong, so without seeing it, I have no idea what your problem might be. You could hire us to take a look, or you may want to reach out to the theme developers as well.
Great. Thank you so much. After a longer period of research finaly I will use this super simple, fancy and short solution for limiting my displayed posts on CTP archive. Like Julie I am very grateful!
THANKS SO MUCH! Was looking for awhile for this solution in order to display all posts on a custom taxonomy archive, and this was EXACTLY what I needed!! Am super grateful!!
Pingback: Display Future Posts Easily with query_posts - WordPress - BJD