WordPress Search Function Notes

by Jeff Starr on Wednesday, July 26, 2006 35 Responses

Code to call an external WordPress search form:

<?php include (TEMPLATEPATH . "/searchform.php"); ?>

Code for a standard, inline WordPress search form:

<form id="searchform" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><input name="s" type="text" id="s" size="33" maxlength="99" />
<input type="submit" class="submit" value="Search &raquo;" /></p>
</form>

Code to search through multiple categories when using customized, individual category pages:

<form id="searchform" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><input name="s" type="text" id="s" size="33" maxlength="99" />
<input type="hidden" name="cat" value="1,2,3,4,5,6" />
<input type="submit" class="submit" value="Search &raquo;" /></p>
</form>

Code to try if the search function fails and your blog is located in a directory other than root:

<form method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">

or:

<form method="get" id="searchform" action="http://yourblog.com/blog/index.php">

This particular search function uses the site URL (note the trailing slash) as the form action, and employs a .gif image as the input type:

<form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">
<div><input type="text" value="Search" name="s" id="s" />
<input type="image" src="<?php bloginfo('stylesheet_directory'); ?>/images/search.gif" id="searchsubmit" value="Search" />
</div></form>

Just for fun, here is bit of php that should (have not checked it yet) output a value indicating the total number of search results:

<?php
$search_count = 0;

$search = new WP_Query("s=$s & showposts=-1");
if($search->have_posts()) : while($search->have_posts()) : $search->the_post();
$search_count++;
endwhile; endif;

echo $search_count;
?>

Another neat trick is to include a default message if some condition is met. For example, here we are telling WordPress to display the text string, "Search Perishable Press", unless someone is actually searching for something:

<?php if (!is_search()) { 
$search_text = "Search Perishable Press"; 
} else { 
$search_text = "$s"; 
} ?>
<form method="get" id="searchform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" id="s" name="s" value="<?php echo wp_specialchars($search_text, 1); ?>" />
<input type="submit" id="searchsubmit" value="Search!" />
</form>

Here is a core hack to get WordPress to search pages in addition to posts for older (1.5) versions of WordPress (I think newer versions do this automatically). Open the file wp-includes/classes.php and look around line #493 for the following code:

if ($this->is_page) {
     $where .= ' AND (post_status = "static")';
} else {
     $where .= ' AND (post_status = "publish")';
}

Replace (comment out) that entire chunk of code and replace it with this:

if ($this->is_page) {
     $where .= ' AND (post_status = "static")';
} elseif ($this->is_search) {
     $where .= ' AND (post_status = "publish" OR post_status = "static")';
} else {
     $where .= ' AND (post_status = "publish")';
}

Happy searching! :)

About the author

[ Jeff Starr ]

Jeff Starr is a web developer, graphic designer and content producer with over 10 years of experience and a passion for quality and detail. Jeff is co-author of the book Digging into WordPress and strives to help people be the best they can be on the Web. + Follow Jeff on Twitter and subscribe to Perishable Press for quality web-design content delivered fresh.


35 Responses

Add a comment

[ Gravatar Icon ]

Roy#1

Hi. I have been asking all around, but my question seems too stupid for anyone to answer it. Now that I run into your overview of WP search function codes, I’ll just give it another try.

I’m trying to change the WP search function so, that it (optional if possible) searches only the post titles. Can this be done by changing the code, do I need a search.php (my classic template doesn’t have one and so far I never needed one) or is there another option?

Thanks in advance.

[ Gravatar Icon ]

Perishable#2

As far as I know, there is no quick-fix, plug-n-play solution to this. By default, WordPress searches everything in the wp_posts table, which includes, among other things, post content and titles. The search form that is used in WP theme templates simply calls to the default function, which is buried elsewhere in the WP core files. There would be no way (that I know of) to modify the default WP search functionality by altering/hacking various theme aspects, including the use of a custom search.php file (which would be used to format search results).

So..

You could either try hacking a search plugin that approximates your target behavior or, better yet, write a plugin from scratch. Two search plugins that come readily to mind are Search All and Search Custom Fields. These two plugins (as well as others) have already obtained a foothold into the core search functionality of WordPress and may provide the clues you need to develop your own custom solution.

One last thing..

Essentially, what you are trying to do via WordPress is achieved relatively simply via direct SQL command:

SELECT * FROM `wp_posts` WHERE `post_title` = 'search terms here'

With a little research, trial and error, it should be possible to incorporate such functionality into WordPress by way of a plugin. If I had more time, I would look into this myself, but unfortunately my schedule is overbooked until the Second Coming. ;)

Good luck!

[ Gravatar Icon ]

beth#3

I have the basic standard search form, and I’m trying to force it to always post in my main content area. Currently, it posts results in it’s own container, which works on my archives page, but I don’t want it to display search results within my sidebar when people search from there.

Is there a way to fix this? Thanks.

[ Gravatar Icon ]

Perishable#4

beth,

Nice to see you again ;)

You have complete control over how WordPress returns your search results, but you need to create an official “search.php” file for your theme in order to do so. As with the single.php file, WordPress will look for the presence of search.php and process search results according to its specifications. If no search.php file is available, WordPress serves the results according to your normal loop functionality. To see this work, create a blank search.php theme file, add the following code, search for something, and examine the results:

<?php get_header(); ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<div class="main-post">
<h1 class="post-title"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
<?php the_content(); ?>
</div>

<?php get_footer(); ?>

With this in place, your search query should be returned on a completely separate page, which is generated by the code located in your new search.php file. Now you are free to completely customize exactly how the search results are displayed. This is the method I use to serve search results here at Perishable Press. Please let me know if you need any further assistance ;)

[ Gravatar Icon ]

mlankton#5

I am finishing up a site change, and search is one of my small problems to fix. I am placing the searchform in the upper right corner, but it is giving some kind of overflow that will affect people on low res monitors. I tried a no-repeat, no luck. Any idea why the search form would be blacking out what is below it?

[ Gravatar Icon ]

Perishable#6

I am not exactly sure what you mean.. I took a look and didn’t see anything out of the ordinary. Could you send a screenshot along with some clarifying information? Thank you ;)

[ Gravatar Icon ]

mlankton#7

I moved the form. I have to have overflow: hidden; in my <h1>, and the search form and the <h1> don’t get along.

I moved the search to my navbar, so it’s right at 1024×768 or better, but any less than that and the site looks bad. Someone not running fullscreen at 1024×768 is going to get a bad looking site. I am not going to lose any more sleep over low res visitors, they are only 22% of my total visitors anyway, and the site is almost where I want it.

Thanks again for all your help.

[ Gravatar Icon ]

beth#8

Thanks again so much for your help.

Strangely enough I have a search.php page, with loop functionality in it. When I went to check it, I overwrote what was on the server with my local copy of the page, and now it works. I must have inadvertently deleted everything in the version on my server. :)

[ Gravatar Icon ]

Perishable#9

Ah yeh, I hate it when that happens..
Glad to hear that everything is back on track :)

[ Gravatar Icon ]

Jeremy Duffy#10

I noticed that your multiple category code only works when you want a post from category 1, 2, OR 3, but not if you only want posts that belong to ALL of the categories listed. I figured out how to do it and posted some sample code here in case you or anyone else needs it:

http://www.jeremyduffy.com/…/wordpress-multiple-categories/

[ Gravatar Icon ]

Perishable#11

Thanks for sharing your script with us, Jeremy! :)

[ Gravatar Icon ]

Podman#12

Thanks for the very well-explained and well-written article on search functions. I was looking all over the web for answers to some scripting issues that I had. Your site was easily the best. Keep up the good work.

[ Gravatar Icon ]

Perishable#13

My pleasure! Thanks for the positive feedback! :)

[ Gravatar Icon ]

prof kienstra#14

Thanks for the input. I liked your script to return the number of posts found after the search, and will definitely be using it in my next theme.

[ Gravatar Icon ]

Perishable#15

Excellent — I am glad you found the information useful. Thank you for the positive feedback :)

[ Gravatar Icon ]

Shane10101#16

I’m trying to figure out how to have the searchpage.php page only display the post titles (& URIs) & the first x words of the returned search results. Could you point me in the right direction?

Thanks :)

[ Gravatar Icon ]

Perishable#17

Have you tried using <?php the_excerpt(); ?> instead of <?php the_content(); ?>? If the default WordPress excerpt lacks the desired functionality, you may want to check out the excellent plugin, the_excerpt Reloaded. As for the post titles, something like <?php the_title(); ?> should do the trick.

[ Gravatar Icon ]

angus#18

Great overview of WP search. I’m wondering if someone has already written something to return search results as XML. Specifically something that another web page could call (web service, .php page, whatever) that outputs XML and could be incorporated with another website.

Thanks!

[ Gravatar Icon ]

Rafael-Brazil#19

Hi i have a question, would appreciate a lot if someone could help me in this….

I’m using WP as CMS and works fine everything BUT, when calling the search function having a little trouble, that is: My site is a multi language site, when searching a item, it still bring me to the default language. i have dutch and english, the default language is dutch, so when someone switch to english and want to search for something the result page shows in dutch, i need to add a something like : if( isset($_GET[’lang’]) ){echo ‘&lang=’.$_GET[lang]; }

[ Gravatar Icon ]

Keith#20

I want to use dropdowns to search multiple categories like here -> http://www.cbonline.org.au/index.cfm?pageId=13,0,31,0

any suggestions on how to best achieve this?

Thanks!

[ Gravatar Icon ]

Kash#21

Hi there,

I’ve been desperately trying to do the same as Keith and failing miserably. I also want to be able to filter by 3 category drop downs AND get the wordpress to spit out the search results in order of relevance.

There are a few plugins that are meant to work, but the application of conditional filters seem to break it… any ideas :)

The plugins are:

http://wordpress.org/extend/plugins/wpsearch/
http://wordpress.org/extend/plugins/wordpress-sphinx-plugin/

I would appreciate your thoughts if you have come across there?

Cheers!

Kash

[ Gravatar Icon ]

Rebecca#22

Dear Jeff,

I want to search one category and its subcategories. SuperSearch plugin is really close to what I want except I don’t want a dropdown of different categories. I want thre to be a built-in function in the search form that only searches one category and its subcategories so that the list is dynamic (rather than manually adding cat=3,4,5)

I would greatly appreciate any advice you can give. Thanks!

[ Gravatar Icon ]

alind#23

nice article, i am new to wordpress, i want my site search to search blogs also, is there any way to achive it. Any wordpress funciton which will give me a array of links for a given string.

i have integrated the wordpress in my site.

i m not getting any solution for this.

i don’t want to search through database directly by writing a query, is their any built in function.

Thanks
alind

[ Gravatar Icon ]

Jeff Starr#24

Hi alind, I think the easiest way to search across multiple sites/domains is to configure a custom search engine using Google:

http://www.google.com/cse/

It is so easy, and quite effective.

[ Gravatar Icon ]

don luttrull#25

I love it when people explain things fully, keep it up.

[ Gravatar Icon ]

NonStop#26

Dude, im trying to replace the search function and i need some help.

I only need to find

wp_specialchars($s, 1);

On title from post, not comments.

Plz help

[ Gravatar Icon ]

Noel#27

I’m trying to do the same thing Kash and Keith above are wanting to do… and your article has come the closest to it yet.

There are multiple, multiple people on the WP forums looking to do this (allow multiple drop downs to filter searches) if you could figure it out this page would become even more popular. :)

[ Gravatar Icon ]

Jeff Starr#28

@NonStop: I know that can be done, but don’t have the time to work it out. You may want to try the WordPress.org forums and someone may already have a solution. Also check the Plugin Directory.

@Noel: I think I recall DysonHat’s WP Smart Sort Premium plugin enable multiple dropdown/sortable menus and other advanced search results. I would start there if nothing else. Sweet gravatar btw :)

[ Gravatar Icon ]

Noel#29

Thanks man!

I actually found a “theme” that had the feature I was looking for as a plug-in in the theme. It was worth the $$ just to save the time in figuring it out myself. The theme / plugin was the “broker” theme here: http://gorillathemes.com/broker/

I will bookmark that link you posted as well though!
Much appreciation!

[ Gravatar Icon ]

Jeff Starr#30

Right on, I will keep that handy and maybe look at abstracting the search functionality as a free plugin. Not sure if I can afford it though ;)

Do you know if the search works with categories, tags, and custom fields? It doesn’t require any XML shenanigans, does it?

[ Gravatar Icon ]

Noel#31

No XML shenanigans. And it works with Categories. I think you could easily adapt it to work with tags and fields though as well. I’m pretty good at hacking around in something once it’s put together… just can’t start it / write it to begin with.

Sort of like I can tell you all sorts of cool Star Wars based stories… but I couldn’t have come up with Vader on my own. ;D haha

[ Gravatar Icon ]

Jeff Starr#32

Yeah same with me — I am primarily a designer who is good at hacking stuff into submission. And I think the community needs a good “advanced-search” plugin, so hopefully I can set aside a bit of time to work on something.

It’s nice to get a fellow Star Wars fan here at Perishable Press. Have you seen this video: http://www.youtube.com/watch?v=dfDEyLbUSxo It’s pretty good ;)

[ Gravatar Icon ]

Noel#33

Oh yeah… seen it and, while it’s hilarious, I’m still amazed at how badly they were able to wear the armor… which was bad to begin with. :D haha

I’m actually the detachment leader for the MEPD (http://forum.mepd.net) - a.k.a. commanding officer for the sandtroopers in the 501st Legion. So yeah, I’m a fan! Good to know you’re one too!

(sorry to high-jack the comments here btw)

[ Gravatar Icon ]

adi#34

hi Jeff, first, thanks alot for this post, it sure gives me an additional knowledge about wp function.

I’ve been search on google and some wp forum, but still can’t find the answer how to change the wp search result permalink. like: domain.com/search/keyword to domain.com/result/keyword. (‘search’ replaced by ‘result’). Can you help me with this problem Jeff? Thanks before.

[ Gravatar Icon ]

adi#35

addition: I can change the search permalink by edit the .httaccess file, the permalink now change to domain.cm/result/keyword, but the search result show a 404 not found message. Please help me how to fix this. Thanks again. :)

Share your thoughts..

Read Comment Policy

Comment Rules: No spam. No profanity. Use your real name. You may use simple HTML tags for style. Wrap all code in <code> tags. Learn more.



Attention: Do NOT follow this link!