Change Search Form HTML – WordPress

Search form is often an overlooked feature when developing new themes. But for content rich wordpress sites it is a must. In this tutorial i will show you 2 easy ways to change the HTML of wordpress search form.

End result will look like this –

First method

First method is using a hook on get_search_form filter.

Open up your functions.php and add the following code

add_filter('get_search_form', 'nexmag_filter_search_form');
function nexmag_filter_search_form( $form ) {
	return '
	<form role="search" method="get" class="search-form" action="">
		<label>
			<span class="screen-reader-text">Search for:</span>
			<input type="search" class="form-control search-field" placeholder="Search …" value="" name="s">
		</label>
		<button class="btn btn-primary search-submit align-top">
			<i class="fas fa-search "></i>	
		</button>
	</form> ';	
}

nexmag_filter_search_form is a custom hook. You can change the name to your own hook. This function accepts the search form as parameter.

<i class="fas fa-search "></i>	

This is an icon class from fontawesome 5.11.2 , so you will need to include the fontawesome library before using this class.

Most of the elements on this form can be customized with some restrictions.

Form element must be present and its action parameter must point to your WordPress path.

The search text input field name must be s. Search will not work if you change the name.

Rest of the elements can be changed – style and all.

second method

Second method is using a custom searchform.php

Create a file searchform.php – at same directory level as functions.php – and paste the form code

<form role="search" method="get" class="search-form" action="">
		<label>
			<span class="screen-reader-text">Search for:</span>
			<input type="search" class="form-control search-field" placeholder="Search …" value="" name="s">
		</label>
		<button class="btn btn-primary search-submit align-top">
			<i class="fas fa-search "></i>	
		</button>
</form>

This form code is same as the first method. But this time you are not using any filter hook to customize it.