WordPress Search Function Notes

Post #168 categorized as Function, WordPress, last updated on Feb 6, 2008
Tagged with notes, php, search, WordPress

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! :)

Subscribe to Perishable Press


22 Responses

TopLeave a comment

[ Gravatar Icon ]

#1Roy

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 ]

#2Perishable

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 ]

#3beth

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 ]

#4Perishable

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 ]

#5mlankton

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 ]

#6Perishable

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 ]

#7mlankton

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 ]

#8beth

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 ]

#9Perishable

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

[ Gravatar Icon ]

#10Jeremy Duffy

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 ]

#11Perishable

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

[ Gravatar Icon ]

#12Podman

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 ]

#13Perishable

My pleasure! Thanks for the positive feedback! :)

[ Gravatar Icon ]

#14prof kienstra

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 ]

#15Perishable

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

[ Gravatar Icon ]

#16Shane10101

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 ]

#17Perishable

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 ]

#18angus

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 ]

#19Rafael-Brazil

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 ]

#20Keith

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 ]

#21Kash

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 ]

#22Rebecca

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!

Share your thoughts..

TopRead official comment policy

The rules are simple. Comment intelligently. Stay on-topic. Don’t spam! Suspected spam will be deleted. Use your real name or nickname, not a site name or business name. Using a site name or business name is a good way to get your link or comment removed. Certain comments are moderated; if your comment does not appear after several days, or if you wish to comment privately, contact me. Also, by posting a comment, you grant this site a perpetual license to reproduce your comment, name, and website URL. Lastly, you may use basic HTML markup, but please do not use <pre> tags. Instead, wrap your code with <code> tags. Use a new set of <code> tags for each code term or phrase, as well as for each individual line of code (i.e., multiple lines of code require multiple code tags). Please see the complete comment policy for more information.