函数文档

set_query_var()

💡 云策文档标注

概述

set_query_var() 函数用于在 WP_Query 类中设置查询变量的值,常用于在模板文件中传递变量。

关键要点

  • 函数接受两个参数:$query_var(字符串,查询变量键)和 $value(混合类型,查询变量值)。
  • 内部通过全局 $wp_query 调用 WP_Query::set() 方法实现。
  • 常用于与 get_template_part() 结合,向模板文件传递数据。
  • 自 WordPress 5.5 起,推荐使用 get_template_part() 的 $args 参数替代 set_query_var() 来传递变量。

代码示例

// 设置查询变量并调用模板
set_query_var('my_form_id', 23);
get_template_part('my-form-template');

// 在模板中获取变量
$my_form_id = get_query_var('my_form_id');

注意事项

  • 避免使用 extract() 函数处理查询变量,因其不符合 WordPress 编码标准,推荐使用 list() 或直接数组访问。
  • 注意函数兼容性,自 WordPress 2.2.0 引入。

📄 原文内容

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

Parameters

$query_varstringrequired
Query variable key.
$valuemixedrequired
Query variable value.

Source

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

Changelog

Version Description
2.2.0 Introduced.

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);
    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 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 : <a href="https://developer.wordpress.org/reference/functions/get_template_part/#comment-4130" rel="ugc">https://developer.wordpress.org/reference/functions/get_template_part/#comment-4130</a>

    Doc about passing arguments to template files :
    https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/