Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

WordPress Search Function Notes

Here is a collection of notes about WordPress search functionality. Note that this post was written a long time ago, so test/verify any code before implementing on a live, production site.

Call/display WP search form

Code to call an external WordPress search form:

<?php get_search_form(); ?>

Code for a standard, inline WordPress search form:

<form method="get" class="search-form" action="/">
	<label for="s" class="search-label"><?php _e('Search:', 'shapespace'); ?></label> 
	<input name="s" class="search-input" id="s" type="text" maxlength="99" placeholder="<?php _e('Search..', 'shapespace'); ?>" value="<?php echo esc_attr(get_search_query()); ?>">
	<input type="submit" class="search-submit" value="<?php _e('Search', 'shapespace'); ?>">
</form>

If your WordPress installation is located in a directory other than root, replace the first line with this:

<form method="get" id="searchform" action="<?php echo esc_url(home_url('/')); ?>">

Remember to test well before going live.

Filtered search

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

<form method="get" class="search-form" action="/">
	<label for="s" class="search-label"><?php _e('Search:', 'shapespace'); ?></label> 
	<input name="s" class="search-input" id="s" type="text" maxlength="99" placeholder="<?php _e('Search..', 'shapespace'); ?>" value="<?php echo esc_attr(get_search_query()); ?>">
	<input type="submit" class="search-submit" value="<?php _e('Search', 'shapespace'); ?>">
	<input type="hidden" name="cat" value="1,2,3,4,5,6" />
</form>

Notice the hidden field? Change the value attribute to reflect whichever categories you would like to filter.

Image submit button

This search form employs a .gif image for the submit button:

<form method="get" class="search-form" action="/">
	<label for="s" class="search-label"><?php _e('Search:', 'shapespace'); ?></label> 
	<input name="s" class="search-input" id="s" type="text" maxlength="99" placeholder="<?php _e('Search..', 'shapespace'); ?>" value="<?php echo esc_attr(get_search_query()); ?>">
	<input type="image" src="/search.jpg" class="search-submit" />
</form>

Edit the image input src with the path to the image you want to use as the submit button.

Display number of search results

Just for fun, here is bit of php that outputs a value indicating the total number of search results:

$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;

Alternately, you can do this:

global $wp_query;
echo $wp_query->found_posts.' results!';

Customize the value attribute

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:

if (!is_search()) { 
	$search_value = "Search Perishable Press"; 
} else { 
	$search_value = esc_attr(get_search_query());; 
}

Then you can do this in your search form:

<input type="text" id="s" name="s" value="<?php echo $search_value; ?>" />

Older WP versions

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 = Fullstack Developer. Book Author. Teacher. Human Being.
BBQ Pro: The fastest firewall to protect your WordPress.

37 responses to “WordPress Search Function Notes”

  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.

  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 (404 link removed 2015/02/10) and Search Custom Fields (404 link removed 2013/10/15). 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!

  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.

  4. Perishable 2007/10/07 9:18 am

    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 ;)

  5. Perishable 2007/10/16 2:21 pm

    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 ;)

  6. 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?

  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.

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

  9. Perishable 2007/10/21 8:45 am

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

  10. Jeremy Duffy 2008/04/11 12:44 pm

    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/computers-internet/wordpress-stuff/wordpress-multiple-categories/

  11. Perishable 2008/04/13 6:59 am

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

  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.

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Blackhole Pro: Trap bad bots in a virtual black hole.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.