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.
- It is quicker by nearly halving the number of database calls
- We separate logic and presentation as much as possible, which should be a ever-present goal in web programming and design
64 Comments
Leave a Reply
About
Welcome to the blog of Ryan Marganti, the owner of SoulSizzle Design. I am currently booked until the end of time and not accepting freelance work. Contact me with any questions or comments.
Categories
Recent Posts
-
Create an Ajax Sorter for WordPress Custom Post Types
Create an AJAX sorter for WordPress custom post types
-
Adding Additional Image Sizes to WordPress Themes
Define and implement Wordpress images resolutions beyond the default Large, Medium, and Thumb sizes.
-
Manage a Boatload of WordPress Sidebars With Help From jQuery
Enhance the Wordpress dashboard with jQuery
-
Display a Different Number of Posts in WordPress Searches
Change the number of results shown in a Wordpress search
Just voted @talenthouse for Chris http://t.co/I1qRfAUh #ladyantebellum #
Wonderful and useful tutorial.. enhanced WordPress Search is better solutions
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;
}
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?
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)
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.
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:
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
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!
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.
[...] 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 [...]
how can I apply this so it just searches the post titles and nothing else?
thanks
It doesn’t work with permalinks set on %postname%… any idea?
[...] Display a different number of posts in wordpress searches [...]
Nicely Done ! I spent four hours trying to figure all this out and then came on your post. Thanks so much !
I am really thankful to this topic because it really gives up to date information *`,
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
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.
Hello, How many Posts we can post on my site in daily. is any limited can provide wordpress site ?..
I as well conceive thus, perfectly indited post! .
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.
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!
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!
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
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
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 ?
Nice blogging man thanks you and thanks wordpress developer who make a Nice blogging system for Us
Great post thanks for sharing!
+1 pour cet article ! Est-il possible de mettre votre lien sur mon facebook vers cet article ?
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!
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
I really enjoy visiting your website! your amazing way to see things is what keeps me fascinated. Thanks so much!!!!
Thank you for sahering this with us. This is what I was desperately looking for and it works like a charm.
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?
Really useful thank you, I do believe your trusty readers may well want more content along these lines keep up the good hard work.
Extremely challenging thanks, I do think your subscribers may perhaps want even more reviews such as this maintain the excellent effort.
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!
[...] 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 [...]
Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing
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.
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.
I really enjoy visiting your website! your amazing way to see things is what keeps me fascinated. Thanks so much!!!!
Fantastic, I spent a lot of hours trying to find something that actually work!
Thanks a lot!
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?
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
how can I apply this so it just searches the post titles and nothing else?
thanks
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!
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
Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing
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!
Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing
Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing
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
You are a rock star. Thank you for this.
[...] 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 [...]
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!!!!
Perfect! Thank you very much for this post!
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.
I as well conceive thus, perfectly indited post! .
Thanks, this is really helpful – so much easier and more efficient than the other methods out there!
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….
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
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
Nice Recommended websites…
I dugg some of you post as I thought they were very useful very useful…
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….
Thank You. Very Helpful!!!