简体   繁体   English

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

[英]Get a variable from another file in wordpress

I'm kind of new to wordpress coding and I've been trying to get a variable from another file.我是 wordpress 编码的新手,我一直在尝试从另一个文件中获取变量。

I have this variable $final_cat_url in /custom/last-category.php that I want to reuse in customtemplate.php.我在 /custom/last-category.php 中有这个变量 $final_cat_url,我想在 customtemplate.php 中重用它。

I've read lots of explanations and the codex, but it's still not working.我已经阅读了很多解释和法典,但它仍然无法正常工作。

I've tried to use the following code in 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'];

Can you help me with that?你能帮我解决这个问题吗? Thanks a lot.非常感谢。

Add this function to your functions.php file:将此函数添加到您的 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;
}

Instead of using get_template_part(), use this:而不是使用 get_template_part(),使用这个:

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

In the file you included:在您包含的文件中:

<?php echo $final_cat_url; ?>

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

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