Hugh's Blog

WordPress 调用模板文件时传递参数

WordPress的 get_template_part() 函数不能向模板传递参数

但其实有个很简单的方法,代码如下,注意要加上文件后缀

include(locate_template('filename.php'));
// locate_template('filename.php', true);

// 直接在子模板文件中使用变量,例如
print_r($var);

另外有人已经封装好方法了 (GitHub)

使用方法

smk_get_template_part('filename.php', array(
   'var' => 'content',
));

// 使用变量
echo $this->var; // Output content

PS:好像直接用 include 或者 require 更方便?…


参考

How to pass variable through get_template_part()