get_query_var()WP 1.5.0

Retrieve variable in the WP_Query class.

1 time — 0.000021 sec (very fast) | 50000 times — 0.06 sec (speed of light)

No Hooks.

Return

Mixed. Contents of the query variable.

Usage

get_query_var( $var, $default );
$var(string) (required)
The variable key to retrieve.
$default(mixed)
Value to return if the query variable is not set.
Default: ''

Examples

0

#1 Get current number of the pagination page:

$paged = get_query_var('paged') ? get_query_var('paged') : 1;

echo 'We are on the page: '. $paged;
0

#2 Current pagination page number on the home page

To get the current pagination number on the main page (it is specified as static, the page template is used), you must use the key page:

$paged = get_query_var('page') ?: 1;
echo "We are on page: ". $paged ." on the main blog page, listed as static.
0

#3 Search request

Get the query that was entered in the search bar on the search results page:

$search_query = get_query_var('s');

echo "Nothing was found for the '$search_query' query";
0

#4 Search query by words

Or we can get the search query separately by words, they are written in the variable search_terms:

$search_terms = get_query_var('search_terms');
print_r($search_terms);

If the query was "pretty pictures" we get:

Array(
	[0] => pretty
	[1] => pictures
)

Notes

  • Global. WP_Query. $wp_query WordPress Query object.

Changelog

Since 1.5.0 Introduced.
Since 3.9.0 The $default argument was introduced.

Code of get_query_var() WP 6.0

function get_query_var( $var, $default = '' ) {
	global $wp_query;
	return $wp_query->get( $var, $default );
}