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

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <div><label class="screen-reader-text" for="s">Search for:</label>
        <input type="text" value="<?php if( is_search() ){ echo get_search_query(); } else { _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>

I hope you find this useful. Enjoy!

Related Posts

NS Weight Release

WP-Backgrounds Lite by InoPlugs Web Design and Juwelier Schönmann 1010 Wien