What Are Query Vars in WordPress?
Definition and Purpose
Query variables in WordPress, known as query vars, are parameters that alter the behavior of WordPress queries by passing values through the URL. These variables filter posts, adjust queries, or trigger specific functions based on their values.
Using get_query_var Function
The get_query_var function retrieves a query variable from the current request. It accepts two parameters:
- $query_var (string, required): The key of the variable to retrieve.
- $default_value (mixed, optional): The value returned if the variable is not set. Defaults to an empty string.
Example Usage
Retrieve a custom query variable:
php
$custom_var = get_query_var('custom_var');
if ($custom_var) {
echo 'The value of custom_var is: ' . esc_html( $custom_var );
}
Retrieve the current page number:
php
$paged = get_query_var('paged');
if ($paged) {
echo 'Current page number: ' . esc_html( $paged );
}
Retrieve the author ID from a query variable:
php
$author_id = get_query_var('author');
if ($author_id) {
echo 'Author ID: ' . esc_html( $author_id );
}
Adding Custom Query Vars
To register a custom query variable, add it to WordPress’s list of public query vars using the query_vars filter.
php
function myplugin_register_query_vars( $vars ) {
$vars[] = 'my_var';
return $vars;
}
add_filter( 'query_vars', 'myplugin_register_query_vars' );
This allows my_var to be accessed via get_query_var(‘my_var’).
Filtering Posts With Custom Query Vars
Use pre_get_posts to modify the query when a custom variable is present.
php
function filter_posts_by_city( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
$city = get_query_var( 'city' );
if ( ! empty( $city ) ) {
$query->set( 'meta_key', 'city' );
$query->set( 'meta_value', $city );
$query->set( 'meta_compare', 'LIKE' );
}
}
add_action( 'pre_get_posts', 'filter_posts_by_city' );
This retrieves the city query variable and filters posts using a custom field.
Custom Rewrite Rules for Query Vars
Rewrite rules convert readable URLs into query vars. To create custom URL formats:
php
function myplugin_rewrite_tag_rule() {
add_rewrite_tag( '%city%', '([^&]+)' );
add_rewrite_rule( '^city/([^/]*)/?', 'index.php?city=$matches[1]', 'top' );
}
add_action('init', 'myplugin_rewrite_tag_rule');
This enables URLs like example.com/city/newyork/ to pass newyork as the city query variable.
Removing or Modifying Query Vars
Query vars can be removed or altered using the query_vars filter.
Remove a custom query variable:
php
remove_filter( 'query_vars', 'myplugin_register_query_vars' );
Modify available query variables:
php
function modify_query_vars( $vars ) {
$vars[] = 'new_var';
return $vars;
}
add_filter( 'query_vars', 'modify_query_vars' );
This method ensures query vars remain manageable and well-structured.