wordpress 函数 set_query_var()

使用方法:

set_query_var( string $var, mixed $value )

Set query variable.(设置查询变量)

参数

$var (string) (Required) Query variable key.

$value (mixed) (Required) Query variable value.

源文件:File: wp-includes/query.php

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

使用例子1:

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:

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

参考:
https://developer.wordpress.org/reference/functions/get_template_part/
https://developer.wordpress.org/reference/functions/set_query_var/
https://developer.wordpress.org/reference/functions/get_query_var/
https://www.wpdaxue.com/wordpress-passes-variables-to-get-template-part.html