简体   繁体   English

通过简码包含php时如何发送变量?

[英]How do you send a variable when including a php via shortcode?

I am including a PHP file on a WordPress page like this: [include filepath='/my_file.php'] The part of the functions.php that I changed to make it possible looks like this: 我在这样的WordPress页面上包含一个PHP文件,如下所示: [include filepath='/my_file.php']我更改为使其成为可能的functions.php部分看起来像这样:

function include_file($atts) {
    extract(shortcode_atts(array('filepath' => NULL), $atts));
    if ($filepath!='NULL' && file_exists( trailingslashit( get_stylesheet_directory() ) . $filepath)){
    ob_start();
    include(get_stylesheet_directory() . '/' . $filepath);
    $content = ob_get_clean();
    return $content;
    }
}

However, I want to be able to send a variable with the include. 但是,我希望能够发送包含变量。 It is not possible like this: [include filepath='/my_file.php?var=1'] , but maybe you get the idea. 不可能这样: [include filepath='/my_file.php?var=1'] ,但也许您明白了。

Right now, I created a lot of different .php files which have the variables in them and included them like this: [include filepath='/my_file1.php'][include filepath='/my_file2.php'] This is really annoying to deal with and if I change something in the original php, every other one has to be changed. 现在,我创建了许多不同的.php文件,这些文件中都包含变量,并且像这样包含它们: [include filepath='/my_file1.php'][include filepath='/my_file2.php']这真令人讨厌处理,如果我更改了原始php中的某些内容,则必须更改其他所有内容。 Is there a better way? 有没有更好的办法? :) :)

You can define a variable before an include statement and that will be visible to the file you are including. 您可以在include语句之前定义一个变量,该变量对您包含的文件可见。

Simple example (I want to pass $foo into my file): 一个简单的例子(我想将$foo传递到我的文件中):

inc.php: inc.php:

echo "inside inc.php '" . $foo . "' << ...\n";

test.php: test.php:

function hello()
{
    $foo = 9999;
    include('inc.php');
}

hello();

which will output: 将输出:

# php test.php
inside inc.php '9999' << ...

hope that helps. 希望能有所帮助。

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

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