metinsaylan // rogue developer

HOWTO: Display WP search term in searchbox

There are many great themes in the WordPress universe. But most of them need some fix to offer the best user experience. In this post, I will show you how to easily display WordPress search term in your blog search box.

Actually this is quite simple, because WordPress already has a function to get the search query. But most of theme authors are quite lazy to put that code in to the right place. So we do the job here. Here are the steps:

  1. Open `searchform.php` in your theme directory. It should look like this: ```php <form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>"> <div> <input type="text" value="<?php _e('Search'); } ?>" name="s" id="s" onfocus="if(this.value == '<?php _e('Search'); ?>'){ this.value = ''; }" onblur="if(this.value == ''){ this.value = '<?php _e('Search'); ?>'; }" /> </div> </form> ``` This is a really simple form with only one input. Yours may be a little different but all search forms have an input field named "s". This is how WordPress search works.
  2. As you can see this field shows only "Search" every time using `value="<?php _e('Search'); } ?>"`. Now we will replace that bit with the following: ```php value="<?php if( is_search() ){ echo get_search_query(); } else { _e('Search'); } ?>" ``` This is all needed. This code will echo search query instead of "Search" if we are on a search results page.
  3. Now save the file and upload it to your server.
  4. All done!

Here is the full searchform.php code after the fix:

&lt;form role=&quot;search&quot; method=&quot;get&quot; id=&quot;searchform&quot; action=&quot;&lt;?php echo home_url( '/' ); ?&gt;&quot;&gt;
    &lt;div&gt;&lt;label class=&quot;screen-reader-text&quot; for=&quot;s&quot;&gt;Search for:&lt;/label&gt;
        &lt;input type=&quot;text&quot; value=&quot;&lt;?php if( is_search() ){ echo get_search_query(); } else { _e('Search'); } ?&gt;&quot; name=&quot;s&quot; id=&quot;s&quot; 
			onfocus=&quot;if(this.value == '&lt;?php _e('Search'); ?&gt;'){ this.value = ''; }&quot;
			onblur=&quot;if(this.value == ''){ this.value = '&lt;?php _e('Search'); ?&gt;'; }&quot;

I hope you find this useful. Enjoy!

Search HOWTO: Display WP search term in searchbox on Google