phpwordpresssearchgenesissearch-form

How to insert a span inside a search form? (Genesis)


When I call genesis_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>

Was looking for a safer alternative to:

add_filter( 'genesis_search_form', 'my_search_button' ); 
function my_search_button( $form ) {
    return str_replace( 
        '<input type="submit"', 
        '<span class="submit-icon"></span><input type="submit"', 
        $form 
    );
}

To avoid replacing the start of a tag. Any ideas?


Solution

  • If you are okay with DOMDocument, this version works better for HTML5.

    add_filter( 'genesis_search_form', 'my_search_button' );
    function my_search_button($form) {
    
        $document = new DOMDocument();
        $document->loadHTML($form);
        $xpath = new DOMXPath($document);
        $input = $xpath->query('//input[@type="submit"]');
        $span = $document->createElement('span');
        $span->setAttribute('class', 'sb-icon');
    
        if ($input->length > 0) {
            $input->item(0)->parentNode->insertBefore($span, $input->item(0));
        }
    
        $document->removeChild($document->doctype); 
        $document->replaceChild($document->firstChild->firstChild->firstChild, $document->firstChild);
        $form_html = $document->saveHTML();
    
        return $form_html;
    }