Display a Different Number of Posts in WordPress Searches

WordPress treats every page/post-listing just about the same. Whether it’s the homepage, a blog category, search results, or even your average page, the same basic logic is used to generate it. This also means that the same settings, including the number of posts displayed per page, are used across the board. However, this is not always desirable.

I have made some changes to the original code that appeared in this article. The new solution is nearly identical to Keith’s below. Though I did arrive at this solution independently, he does deserve some acknowledgment for beating me to the punch.

The Goal

The basic goal of a site search is to find information quickly; however, it is becoming more and more commonplace to see increasingly stylized post listings. In my eyes, this runs the risk of becoming counter-intuitive to this goal. Because of this, it is my personal preference to simplify my search results and to show more results. Because searches rely on the same setting (found in Settings » Reading » Blog pages show at most) as any other WordPress page when determining the number of listings to show, we have to get a little creative in order to show a different am amount.

How Not to Do It

Most blog posts or WordPress.org forum posts will recommend using the query_posts() function in order to alter the number of search listings shown. They advise inserting something similar before the loop in your themes search.php.

However, this neglects one important fact. WordPress already runs the query once before it even gets to this query_posts() call. This means that you are essentially doubling the number of database calls WordPress needs to do in order to retrieve the correct number of posts. If an efficient, quickly-loading site is important to you (I know it is to me), this should be a concern. This is even more important with the recent news that Google is now incorporating page-load time into its pagerank algorithm.

A Better Solution

The obvious solution is to alter the original query before it is executed. This is made fairly simple with WordPress filters (noticing a common theme in our WordPress-related posts?). Using the pre_get_posts filter, we can change the query parameters before it is translated into an actual MySQL query. Simply insert the following code into the functions.php file of your theme. It’s so simple, I hope this technique will become more commonplace.

function change_wp_search_size($query) {
	if ( $query->is_search ) // Make sure it is a search page
		$query->query_vars['posts_per_page'] = 10; // Change 10 to the number of posts you would like to show
 
	return $query; // Return our modified query variables
}
add_filter('pre_get_posts', 'change_wp_search_size'); // Hook our custom function onto the request filter

Any function that is hooked into the pre_get_posts filter will automatically be passed an WP_Query Object containing any parameters that intends to use to generate the database query. All we have to do is change the posts_per_page parameter to the number of results we would like to show.

We must first determine if we are even on the search results page. This is as easy as testing to see if $query->is_search is set. Then, it’s simply a matter of returning our modified query paramaters to WordPress and letting WordPress do it’s magic.

A few additional notes

If you don’t want to limit the number of posts shown at all, simply set $query->query_varts['posts_per_page'] to -1. Also, this technique is not limited to the search page only. You can also test for $query->is_cateogry, $query->is_tag, $query->is_archive, $query->is_date, and etc. And if you want to test for a specific category you can use a conditional statement similar to the following:

if ($query->query_vars['cateogry_name'] == 'category_slug')

The Wrap-up

Though this solution may contain a few more lines of code than a query_posts() solution, it is still superior for two reasons.

  1. It is quicker by nearly halving the number of database calls
  2. We separate logic and presentation as much as possible, which should be a ever-present goal in web programming and design

64 Comments

  1. GPL WP ThemesApril 26, 2010

    Wonderful and useful tutorial.. enhanced WordPress Search is better solutions

     
  2. KeithApril 26, 2010

    Hey, thanks this got me on the right track so thank you, but I had to hook into pre_get_posts instead. I’m on WordPress 3 Beta so maybe things have changed. Here’s my code:

    add_filter(‘pre_get_posts’, ‘change_wp_search_size’);

    function change_wp_search_size($queryVars) {
    $no_paging = array(‘projects’, ‘downloads’, ‘slideshow’);
    if(in_array($queryVars->query_vars['post_type'], $no_paging))
    $queryVars->query_vars['posts_per_page'] = -1;
    return $queryVars;
    }

     
  3. osamaMay 10, 2010

    What if i need to display all posts in category,tag,search,archive pages what is the needed code to overcome the default number of wordpress posts?

     
  4. DannyJuly 4, 2010

    That is excellent, Ryan. Thank you very much.
    I am not a PHP coder so I would like to ask the same question as Osama:
    How can it be adapted for other page types, like Category contents (my main forcus right now)

     
  5. soulsizzleJuly 12, 2010

    osoma and Danny,

    Since writing this article, I have switched to an implementation similar to Keith’s code above. This can be modified to work with categories, tags, etc. For example, the following will work if we are on a Category page.

    function change_number_of_posts($query) {
    	if ( $query->is_category ) // Make sure it is a category page
    	$query->query_vars['posts_per_page'] = 10; // Change 10 to the number of posts you would like to show
    	return $query; // Return our modified query variables
    }
    add_filter('pre_get_posts', 'change_number_of_posts'); // Hook our custom function onto the request filter

    Note, if you want to list ALL posts, 10 should be changed to -1. You can also use is_tag, is_archive, is_date, etc instead of is_category.

    If you want to test for a specific category, change your conditional statement to the following:

    if ($query->query_vars['category_name'] == 'The Category')

     
  6. Lou SparxSeptember 26, 2010

    I display related posts on single posts and unfortunately this code changes how many related posts are shown :(

    Man I was so happy because it does do what it’s suppose to do but it also does it to other things as well. ARRRGGG.

    Is there a way to apply this code ONLY to category pages?

    Thanks for another reliable wordpress source ;)

    Lou

     
  7. Andy TehOctober 2, 2010

    Brilliant! I spent most of the day searching for a way to change the number of posts for category pages (default = 12) to 6 for only one category page. As you pointed out in your post, many others suggest query_posts() which didn’t work for me. I now have things exactly how I like them. Many thanks!

     
  8. marcOctober 13, 2010

    Another reason why *not* to use query_posts() is that it does not work :)

    Try halving the number of results per page with query_posts(). This doubles the number of result pages, but WP will only let you access the first half of the result pages.

    This is because query_posts() does not alter the algorithm to determine the total number of result pages. WP will hence think that the second half of the result pages are invalid (out of bounds).

    Cheers,
    Marc.

     
  9. Razee » Blog Archive » How to Display Different Numbers of PostsNovember 3, 2010

    [...] Display different number of Posts Tutorial To Display a Different Number of Post on Search Result Display a different number of posts in wordpress searches [...]

     
  10. spannerNovember 17, 2010

    how can I apply this so it just searches the post titles and nothing else?

    thanks

     
  11. manuelNovember 27, 2010

    It doesn’t work with permalinks set on %postname%… any idea?

     
  12. Razee » Blog Archive » How to Turns WordPress’ basic search into a full textDecember 17, 2010

    [...] Display a different number of posts in wordpress searches [...]

     
  13. The Dividend NinjaDecember 27, 2010

    Nicely Done ! I spent four hours trying to figure all this out and then came on your post. Thanks so much !

     
  14. Esteban FioravantiJanuary 19, 2011

    I am really thankful to this topic because it really gives up to date information *`,

     
  15. NadeemMarch 14, 2011

    I am greatfully Thanks to you that you solved my problem i have read many blogs and search on google but didn’t find any solution but your blogs help me a lot. wish u a Happy life dear.Thanks

     
  16. Dave StrombergerMarch 25, 2011

    Excellent post, thank you! I might add that by changing $query->is_category to ! is_front_page(), the number of results returned for tag and category searches will also be changed.

     
  17. GaneshMay 5, 2011

    Hello, How many Posts we can post on my site in daily. is any limited can provide wordpress site ?..

     
  18. aplicatii iphoneMay 21, 2011

    I as well conceive thus, perfectly indited post! .

     
  19. daniel mamann puerto vallartaJune 2, 2011

    Hi there, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam responses? If so how do you reduce it, any plugin or anything you can suggest? I get so much lately it’s driving me mad so any assistance is very much appreciated.

     
  20. daniel mamann resortJune 2, 2011

    Greetings! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a outstanding job!

     
  21. daniel mamannJune 2, 2011

    Hi! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy reading your articles. Can you suggest any other blogs/websites/forums that cover the same subjects? Thanks for your time!

     
  22. daniel mamann puerto vallartaJune 2, 2011

    Hello! Would you mind if I share your blog with my zynga group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Thanks

     
  23. Murder 2 SongsJuly 23, 2011

    I am greatfully Thanks to you that you solved my problem i have read many blogs and search on google but didn’t find any solution but your blogs help me a lot. wish u a Happy life dear.Thanks

     
  24. Murder 2 SongsJuly 23, 2011

    any one help me i wanna show filter post show on blog home
    like 5 post from 1 category 5 post from 4th category like that any php developer for help ?

     
  25. Online CalculatorJuly 23, 2011

    Nice blogging man thanks you and thanks wordpress developer who make a Nice blogging system for Us

     
  26. Pasquale JandaJuly 29, 2011

    Great post thanks for sharing!

     
  27. Seo googleJuly 29, 2011

    +1 pour cet article ! Est-il possible de mettre votre lien sur mon facebook vers cet article ?

     
  28. Zvonimir BaraćJuly 30, 2011

    It’s just what I needed for my archive pages. I have dual archives for two languages and they would be split into 5 titles which looked rather silly. Thanks dude, you are awesome!

     
  29. soniaAugust 1, 2011

    hi friendssss iam sonia from hafizabad panjab friends ye no mujh tang kerta he name asif plz kujh kero us ka sala therki he tang kerta he girls ko ulo benata he un ko dhoka deta he plz note this number ye sub us ke no he asif ky sub 03436121038/ 03034546988/ 03348239311/ 03366296956/ 03446241662/ friends beri mushkil se us ke sub no nikaly hein me ne plz us ka kujh kero plzzzzzzzz plzzzz plzzzzz

     
  30. electronic cig reviewsAugust 16, 2011

    I really enjoy visiting your website! your amazing way to see things is what keeps me fascinated. Thanks so much!!!!

     
  31. GuitareAugust 27, 2011

    Thank you for sahering this with us. This is what I was desperately looking for and it works like a charm. ;-)

     
  32. JeffSeptember 1, 2011

    Is is possible to include multiple definitions in the functions.php so that I can customize the results lengths for different page types? As in show 10 posts on the main page, 25 posts on categories pages, and no limit (-1) on archive pages?

     
  33. Michael JeffersonSeptember 5, 2011

    Really useful thank you, I do believe your trusty readers may well want more content along these lines keep up the good hard work.

     
  34. {Jim|Andy|Bob|Reginald|Frank|Joe|William|September 5, 2011

    Extremely challenging thanks, I do think your subscribers may perhaps want even more reviews such as this maintain the excellent effort.

     
  35. Daily NewsSeptember 14, 2011

    Hi! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy reading your articles. Can you suggest any other blogs/websites/forums that cover the same subjects? Thanks for your time!

     
  36. WordPress Arena: A Blog for WordPress Developers, Designers and BloggerSeptember 21, 2011

    [...] WordPress’ search function suck Less. How to Turns WordPress’ basic search into a full text Display a different number of posts in wordpress searches How To: Building a Google Custom Search Engine (GCSE) into Your WordPress [...]

     
  37. Live Criket ScoreSeptember 30, 2011

    Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing

     
  38. Ian DunnOctober 7, 2011

    Just a minor correction: pre_get_posts is an action, not a filter. You should be hooking in with add_action() instead of add_filter(), and the callback function shouldn’t return anything.

    The $query variable is passed by reference, so it isn’t a copy of the $query variable inside WP_Query::get_posts(), it’s a link directly to it. Any changes to $query inside the callback function will be applied to the variable in the calling function.

     
  39. MatthOctober 11, 2011

    Thanks for sharing this solution. A year and a half later, it’s still the best instruction I can find on how to do this.

    I cut down just my homepage to 5 posts using if ( $query->is_home ), while leaving 10 on all the other pages. I got it working in about 35 seconds, so thank you.

     
  40. GMIOctober 13, 2011

    I really enjoy visiting your website! your amazing way to see things is what keeps me fascinated. Thanks so much!!!!

     
  41. HeshamOctober 29, 2011

    Fantastic, I spent a lot of hours trying to find something that actually work!

    Thanks a lot!

     
  42. NSDL PanNovember 29, 2011

    Is is possible to include multiple definitions in the functions.php so that I can customize the results lengths for different page types? As in show 10 posts on the main page, 25 posts on categories pages, and no limit (-1) on archive pages?

     
  43. Send Flowers OnlineNovember 29, 2011

    Hello! Would you mind if I share your blog with my zynga group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Thanks

     
  44. Fun PkNovember 29, 2011

    how can I apply this so it just searches the post titles and nothing else?

    thanks

     
  45. Pan Card OnlineNovember 29, 2011

    Greetings! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a outstanding job!

     
  46. Online StoreNovember 29, 2011

    I am greatfully Thanks to you that you solved my problem i have read many blogs and search on google but didn’t find any solution but your blogs help me a lot. wish u a Happy life dear.Thanks

     
  47. Entertainment NewsDecember 2, 2011

    Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing

     
  48. Microsoft.Net Framework 4December 14, 2011

    It’s just what I needed for my archive pages. I have dual archives for two languages and they would be split into 5 titles which looked rather silly. Thanks dude, you are awesome!

     
  49. Jannat 2 songsDecember 30, 2011

    Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing

     
  50. zoomagazinJanuary 11, 2012

    Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing

     
  51. Cosmetice RomaniaJanuary 12, 2012

    Cosmetice Romania is a network marketing company of Romania dealing in cosmetics products. Cosmetice Romania is working in almost every famous country like UK , USA , Canada and many other. Cosmetice Romania is a trust worthy and reliable company to join and work with. According to company

     
  52. KaitJanuary 21, 2012

    You are a rock star. Thank you for this.

     
  53. kAtypical Services » Blog Archive » Making the WordPress Search Better.January 21, 2012

    [...] on the WordPress search function needs to happen. I vote that Ryan Marganti get some credit for this little beauty from his blog. This allows you to set how many results show on a search page. It could of course be modified with [...]

     
  54. SamiJanuary 30, 2012

    Thank you soo much for this although I am having an issue modifying the code (I’m sure I’m doing it wrong. I am trying to apply it to searches, archives, categories and tags (basically anything except for the front page).

    Are you able to advise how to do this?

    Thank you!!!!

     
  55. cherylFebruary 9, 2012

    Perfect! Thank you very much for this post!

     
  56. Technology NewsFebruary 10, 2012

    Thanks for sharing this solution. A year and a half later, it’s still the best instruction I can find on how to do this.

    I cut down just my homepage to 5 posts using if ( $query->is_home ), while leaving 10 on all the other pages. I got it working in about 35 seconds, so thank you.

     
  57. Awarapan 2February 20, 2012

    I as well conceive thus, perfectly indited post! .

     
  58. Charlotte ColemanMarch 29, 2012

    Thanks, this is really helpful – so much easier and more efficient than the other methods out there!

     
  59. Visit IndonesiaApril 4, 2012

    Good article…

    I think you’ve got a lot of readers that are more than thankful to you and really pleased with the content on your blog, making me fantastically interested in what post will be next and about….

     
  60. Electric Sport CarApril 23, 2012

    You saved my day mate!
    that is what i was looking for. it easy and quick solution, so need to another plugin. top!

    cheers & thx

    dean

     
  61. Electric Sport CarApril 23, 2012

    Do you know simple code that will allow me to display search results only from 1 category? for example any post related to ‘house’ but only if post is in category id=1,5 or 6?

    love your quick codes. cheers

     
  62. Metabolic SyndromeMay 11, 2012

    Nice Recommended websites…

    I dugg some of you post as I thought they were very useful very useful…

     
  63. cardiovascular systemMay 15, 2012

    Cool website…

    I am no longer certain the place you’re getting your information, but great topic. I must spend some time finding out much more or figuring out more. Thanks for excellent info I was searching for this info for my mission….

     
  64. WebpaulMay 17, 2012

    Thank You. Very Helpful!!!

     

Leave a Reply