dongtiao2105 2016-07-27 09:39
浏览 39
已采纳

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

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:

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.

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. Is there a better way? :)

  • 写回答

1条回答 默认 最新

  • douya6606 2016-07-27 09:45
    关注

    You can define a variable before an include statement and that will be visible to the file you are including.

    Simple example (I want to pass $foo into my file):

    inc.php:

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

    test.php:

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

    which will output:

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

    hope that helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵