get_query_var()
Gets query variables (query parameters) from WP_Query, which is set in the global variable $wp_query.
To set a query variable, use set_query_var()
No Hooks.
Returns
Mixed. Various values of the variables.
Usage
$var = get_query_var( $var, $default );
- $var(string) (required)
- Key of the variable to retrieve.
- $default(string) (WP 3.9)
- Value to return if the requested parameter is not set.
Default: ''
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 )
List of all keys in get_query_var('key').
Some values are populated on the corresponding pages. For example, we cannot get the query parameters search_terms or s, if we try to retrieve them not on the search page - these parameters will be empty on all pages except for the search page.
cpage — Comments page paged — Pagination s — Search query search_terms — Search words array() page — 0 pagename — For example, if the page is called "Page", it will be - stranica error post_parent attachment attachment_id name — Post name static page_id — 0 category_name — Uncategorized tag cat taxonomy tag_id meta_key meta_value author_name preview post_type posts_per_page — 10 comments_per_page — 10 order — DESC second minute hour day — 0 monthnum — 0 year — 0 // and more subpost subpost_id w — 0 sentence fields menu_order feed m — 0 p — 0 tb ignore_sticky_posts suppress_filters cache_results update_post_term_cache — 1 update_post_meta_cache — 1 nopaging no_found_rows category__in — Array() category__not_in — Array() category__and — Array() post__in — Array() post__not_in — Array() tag__in — Array() tag__not_in — Array() tag__and — Array() tag_slug__in — Array() tag_slug__and — Array()
Notes
- Global. WP_Query.
$wp_queryWordPress 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 7.0
function get_query_var( $query_var, $default_value = '' ) {
global $wp_query;
return $wp_query->get( $query_var, $default_value );
}