get_query_var()
Retrieve variable in the WP_Query class.
Uses: WP_Query::get()
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( $query_var, $default_value );
- $query_var(string) (required)
- The variable key to retrieve.
- $default_value(mixed)
- Value to return if the query variable is not set.
Default: empty string
Examples
#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;
#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.
#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";
#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_value argument was introduced. |
get_query_var() get query var code WP 6.7.1
function get_query_var( $query_var, $default_value = '' ) { global $wp_query; return $wp_query->get( $query_var, $default_value ); }