How to properly sanitize user input in WordPress search form: get_search_query()

669 views Asked by At

I am attempting to sanitize user input for a search form that I am building in WordPress (in searchform.php file).

I used a built-in WordPress function, sanitize_text_field():

function wpdocs_my_search_form( $form ) {
    $search_query = sanitize_text_field( get_search_query() );
    
    $form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
    <div><label class="screen-reader-text" for="s">' . __( 'Search for:' ) . '</label>
    <input type="text" value="' . $search_query . '" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
    </div>
    </form>';

    return $form;
}
add_filter( 'get_search_form', 'wpdocs_my_search_form' );

This however, is still not properly sanitizing input such as <script></script>

I also attempted to add additional code to detect if it has been submitted however, that is also not working. I would appreciate any direction/pointers.

0

There are 0 answers