set_query_var( string $var, mixed $value )

Set query variable.


Description Description


Parameters Parameters

$var

(string) (Required) Query variable key.

$value

(mixed) (Required) Query variable value.


Top ↑

Source Source

File: wp-includes/query.php

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

Top ↑

Changelog Changelog

Changelog
Version Description
2.2.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by stode

    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);
    get_template_part('my-form-template');
    

    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 2 content
    Contributed by Đăng Tú

    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
    

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