Using WordPress ‘get_search_query()’ PHP function

The get_search_query() WordPress PHP function retrieves the contents of the search WordPress query variable.


echo get_search_query();


  • $escaped (bool) Optional – Whether the result is escaped. Only use when you are later escaping it. Do not use unescaped. Default: true.

More information

See WordPress Developer Resources: get_search_query()


Display search query in a search form

This code displays the search query within the search form input field.

<input type="search" name="s" value="<?php echo get_search_query(); ?>" />

Show search query in a message

This code displays a message showing the search query used by the user.

$search_query = get_search_query();
echo 'You searched for: ' . $search_query;

Use search query in a conditional

This code checks if the search query contains the word “WordPress” and displays a message accordingly.

$search_query = get_search_query();
if (strpos($search_query, 'WordPress') !== false) {
    echo 'You searched for something related to WordPress!';
} else {
    echo 'You did not search for anything related to WordPress.';

Modify search query before displaying

This code retrieves the search query, adds “Hello, ” before it, and then displays it.

$search_query = get_search_query();
$modified_query = 'Hello, ' . $search_query;
echo $modified_query;

Use unescaped search query for further processing

This code retrieves the unescaped search query and processes it with a custom function process_search_query().

$unescaped_search_query = get_search_query(false);
$processed_query = process_search_query($unescaped_search_query);
echo $processed_query;

function process_search_query($query) {
    // Custom processing logic
    return $query;