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.

Return

null. Nothing.

Usage

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

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.1.1

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