When I call get_search_form()
, it outputs:
<form class="search-form">
<meta itemprop="target">
<input type="search">
<input type="submit">
</form>
But I wanted it to generate with a span
inside, like:
<form class="search-form">
<meta itemprop="target">
<input type="search">
<span class="submit-icon"></span>
<input type="submit">
</form>
Any ideas?
If we look at the source code of get_search_form()
, notice that before the form gets rendered, the search_form_format
filter hook gets fired. We can use that to add another filter attached to get_search_form
where the callback is dependent upon the format.
add_filter( 'search_form_format', 'wpse_259716_search_form_format', 99, 1 );
function wpse_259716_search_form_format( $format ) {
if( in_array( $format, array( 'xhtml', 'html5' ) ) ) {
add_filter( 'get_search_form', "wpse_259716_get_search_form_$format", 99, 1 );
}
return $format;
}
function wpse_259716_get_search_form_xhtml( $form ) {
$search="<input type="submit"";
$xhtml="some xhtml";
$replace = $xhtml . $search;
return str_replace( $search, $replace, $form );
}
function wpse_259716_get_search_form_html5( $form ) {
$search="<input type="submit"";
$html5 = 'some html5';
$replace = $html5 . $search;
return str_replace( $search, $replace, $form );
}
Alternatively, you could use a class-based approach.
$wpse_259716 = new wpse_259716();
add_filter( 'search_form_format', array( $wpse_259716, 'search_form_format' ), 99, 1 );
add_filter( 'get_search_form', array( $wpse_259716, 'get_search_form' ), 99, 1 );
class wpse_259716 {
protected $format;
public function search_form_format( $format ) {
return $this->format = $format;
}
public function get_search_form( $form ) {
$search = $replace="<input type="submit"";
if( 'xhtml' === $this->format ) {
$xhtml="some xhtml";
$replace = $xhmtl . $search;
}
elseif( 'html5' === $this->format ) {
$html5 = 'some html5';
$replace = $html5 . $search;
}
return str_replace( $search, $replace, $form );
}
}