set_query_var()WP 2.2.0

Sets the value of a query variable in the WP_Query class.

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.


null. Nothing (null).


set_query_var( $query_var, $value );
$query_var(string) (required)
Query variable key.
$value(mixed) (required)
Query variable value.



#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

#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().


  • Global. WP_Query. $wp_query WordPress Query object.


Since 2.2.0 Introduced.

set_query_var() code WP 6.4.3

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