get_search_query()WP 2.3.0

Retrieves the contents of the search WordPress query variable.

The search query string is passed through esc_attr() to ensure that it is safe for placing in an HTML attribute.

Hooks from the function

Return

String. Search query.

Usage

get_search_query( $escaped );
$escaped(true|false)
Whether the result is escaped. Only use when you are later escaping it. Do not use unescaped.
Default: true

Examples

0

#1 Output the search query string

Let's say the user searched for the word "WordPress". The following code print this word:

<?php echo get_search_query(); ?>
0

#2 Output to a variable

When you need to get the result to a variable, use such code:

$search_query = get_search_query();
0

#3 Spaces in the search bar

The function does not remove spaces at the ends of the search string. For example:

// the search contains a string with spaces at the ends " mail me "
get_search_query(); // ` mail me `

You can delete spaces like this:

$squery = trim( get_search_query() );

Changelog

Since 2.3.0 Introduced.

Code of get_search_query() WP 5.9.3

function get_search_query( $escaped = true ) {
	/**
	 * Filters the contents of the search query variable.
	 *
	 * @since 2.3.0
	 *
	 * @param mixed $search Contents of the search query variable.
	 */
	$query = apply_filters( 'get_search_query', get_query_var( 's' ) );

	if ( $escaped ) {
		$query = esc_attr( $query );
	}
	return $query;
}