Using WordPress ‘get_search_query’ PHP filter

The get_search_query WordPress PHP filter allows you to modify the contents of the search query variable.

Usage

add_filter( 'get_search_query', 'your_custom_function' );

function your_custom_function( $search ) {
    // your custom code here
    return $search;
}

Parameters

  • $search (mixed): Contents of the search query variable.

More information

See WordPress Developer Resources: get_search_query

Examples

Remove special characters from search query

Remove special characters from the search query for better search results.

add_filter( 'get_search_query', 'remove_special_chars' );

function remove_special_chars( $search ) {
    $search = preg_replace( '/[^a-zA-Z0-9\s]/', '', $search );
    return $search;
}

Convert search query to lowercase

Convert the search query to lowercase to improve search result matching.

add_filter( 'get_search_query', 'convert_to_lowercase' );

function convert_to_lowercase( $search ) {
    $search = strtolower( $search );
    return $search;
}

Limit search query length

Limit the search query length to a maximum of 50 characters.

add_filter( 'get_search_query', 'limit_search_query_length' );

function limit_search_query_length( $search ) {
    $search = substr( $search, 0, 50 );
    return $search;
}

Replace specific words in the search query

Replace specific words in the search query to improve search results.

add_filter( 'get_search_query', 'replace_specific_words' );

function replace_specific_words( $search ) {
    $search = str_replace( 'old_word', 'new_word', $search );
    return $search;
}

Add a prefix to the search query

Add a specific prefix to the search query for targeted results.

add_filter( 'get_search_query', 'add_search_query_prefix' );

function add_search_query_prefix( $search ) {
    $search = 'prefix_' . $search;
    return $search;
}