set_query_var( string $query_var, mixed $value )

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


Query variable key.
Query variable value.


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



User Contributed Notes

  1. Skip to note 4 content

    One use case for this is to pass variable to template file when calling it with get_template_part().

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

    Now in you template you can then call it.

    // Inside my-form-template.php
    $my_form_id = get_query_var('my_form_id');
  2. Skip to note 5 content
    Anonymous User

    This is a way to pass variables to the called files.

    On the a.php file:

    $sample = 'a sample variable';
    $year = 2019;
    $arr = [
    	'sample' => $sample,
    	'year' => $year
    set_query_var( 'multiVar', $arr );
    get_template_part( 'b' );
    get_template_part( 'c' );

    On the b.php file:

    $arr = get_query_var( 'multiVar' );
    echo $arr['year']; // This will print out: 1995

    On the c.php file:

    $arr = get_query_var( 'multiVar' );
    echo $arr['sample']; // This will print out: a sample variable
  3. Skip to note 6 content

    To update examples and avoid spread of set_query_var() in recents projects.
    Lot of them continue to use set_query_var() for passing args/vars to a template with get_template_part().
    Since WordPress 5.5 (08/11/2020), think to use the $args third parameter to passed args to a template or a partial.

    // No example here as this is not the appropriate page
    But for example with get_template_part :

    Doc about passing arguments to template files :

You must log in before being able to contribute a note or feedback.