【发布时间】:2021-12-20 16:57:47
【问题描述】:
我是 wordpress 编码的新手,我一直在尝试从另一个文件中获取变量。
我在 /custom/last-category.php 中有这个变量 $final_cat_url,我想在 customtemplate.php 中重用它。
我已经阅读了很多解释和法典,但仍然无法正常工作。
我尝试在 customtemplate.php 中使用以下代码
get_template_part( 'custom/last-category', null, array('my_final_cat_url'=> $final_cat_url));
echo $args['my_final_cat_url'];
你能帮我解决这个问题吗?非常感谢。
【问题讨论】:
-
当您使用
get_template_part()时,您将参数传递到模板部分。当您传入变量时,您可以在模板部分本身中使用像echo $args['key'];这样的变量。我不确切知道您要做什么,但最好在其他地方生成变量并将其传递到模板中,而不是在模板中生成它并尝试从那里检索它。 developer.wordpress.org/reference/functions/get_template_part -
感谢您的回复。我创建 last-category.php 只是为了生成这个变量 #final_cat_url 因为我想在三个 customtemplate1.php 文件(2、3、4)中重用它,例如:我有一个滑块代码(带有一些 php 和 html 代码) 我用 get_template_part() 重用它没关系,但变量似乎很复杂。回声 $args['key'];这个'key'参数可以是像$key这样的变量,它会返回一个值吗? ..我只是不明白在这种情况下“关键”是什么意思。非常感谢您的关注。
-
我建议将变量作为参考而不是作为参数传递,如果我理解您通过 get_template_part() 将 $final_cat_url 发送到 custom/last-category.php,那么当您将该变量发送到模板,实际上您正在发送一个副本,如果您想重用在 last-category.php 中处理的值,您必须作为参考发送: get_template_part( 'custom/last-category', null, array( 'my_final_cat_url'=> &$final_cat_url));现在您可以重用 customtemplate.php 中 $final_cat_url 的值,并在 last-category.php 中处理新值
-
你不能在customtemplate.php中得到
$final_cat_url吗?然后你可以使用get_template_part()三次,从那里的三个模板部分中的每一个使用一次。或者,如果您正在制作主题,您可以在 functions.php 中制作一个函数并从那里使用它。 codex.wordpress.org/Functions_File_Explained -
@Cristino ,非常感谢您的回复和您的时间。我还在想办法。
标签: php arrays wordpress variables