繁体   English   中英

从 wordpress 中的另一个文件获取变量

[英]Get a variable from another file in wordpress

我是 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'];

你能帮我解决这个问题吗? 非常感谢。

将此函数添加到您的 functions.php 文件中:

function includeWithVariables($filePath, $variables = array(), $print = true){
    $output = NULL;
    if(file_exists($filePath)){
        // Extract the variables to a local namespace
        extract($variables);

        // Start output buffering
        ob_start();

        // Include the template file
        include $filePath;

        // End buffering and return its contents
        $output = ob_get_clean();
    }
    if ($print) {
        print $output;
    }
    return $output;
}

而不是使用 get_template_part(),使用这个:

<?php includeWithVariables('file_to_include.php', array('final_cat_url' => $final_cat_url)); ?>

在您包含的文件中:

<?php echo $final_cat_url; ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM