set_query_var()WP 2.2.0

Sets the query parameter in the global variable $wp_query.

A variable is set that is located in the property of the object $wp_query->query_vars. These parameters can be retrieved using get_query_var() or like this:

global $wp_query;
$wp_query->query_vars[ $query_var ]
1 time — 0.000015 sec (very fast) | 50000 times — 0.01 sec (speed of light) | PHP 7.0.2, WP 4.4.1

No Hooks.

Returns

null. Nothing.

Usage

set_query_var( $var, $value );
$var(string) (required)
The name of the parameter. Key.
$value(mixed) (required)
The value of the parameter.

Examples

0

#1 Set the query parameter and then get it

// set up
set_query_var( 'comments_per_page', 20 );

//we get
$var = get_query_var( 'comments_per_page' );
echo $var; // 20
0

#2 Passing a variable to a template file

You can use the parameter setting for example to send data to a template file when you call it with get_template_part().

// When calling a template with get_template_part()
set_query_var( 'my_form_id', 23 );
get_template_part( 'my-form-template' );

Now in the code of the template file the data can be obtained as follows:

// Inside my-form-template.php
$my_form_id = get_query_var('my_form_id');

Since WP 5.5 you can pass data to the template file through the third parameter of get_template_part().

Notes

  • Global. WP_Query. $wp_query WordPress Query object.

Changelog

Since 2.2.0 Introduced.

set_query_var() code WP 6.9

function set_query_var( $query_var, $value ) {
	global $wp_query;
	$wp_query->set( $query_var, $value );
}