You need to enable JavaScript to run this app. PHP如何将时间戳设为常量实现WordPress上传文件共用同一时间戳文件夹
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何将时间戳设为常量实现WordPress上传文件共用同一时间戳文件夹

问题原因

你的写法存在两个核心问题导致取不到变量:

  • 你给wfu_before_file_check的回调函数额外加了第三个$time入参,但这个钩子本身只会传递2个参数,你额外定义的参数不会被系统自动赋值。
  • 全局变量/常量失效大概率是执行顺序问题:要么是你定义变量/常量之前,钩子就已经被注册执行;要么是变量作用域声明错误。

最优解决方案:用闭包继承父作用域变量

PHP支持通过匿名函数(闭包)的use语法直接引入外部作用域的变量,不需要修改全局状态,兼容性最好:

$time = date("h:i:s");

if (!function_exists('wfu_before_file_check_handler')) {
    // 通过use引入外部定义的$time,固定值不需要加引用符号&
    add_filter('wfu_before_file_check', function($changable_data, $additional_data) use ($time) {
        $changable_data["file_path"] = str_replace("%time%", $time, $changable_data["file_path"]);
        return $changable_data;
    }, 10, 2); 
}

命名函数兼容方案

如果你必须用命名函数的写法,可以通过$GLOBALS超全局数组传递变量,避免作用域问题:

// 提前把时间存入超全局数组,键名建议自定义避免冲突
$GLOBALS['wf_custom_upload_time'] = date("h:i:s");

if (!function_exists('wfu_before_file_check_handler')) {
    function wfu_before_file_check_handler($changable_data, $additional_data){
        $changable_data["file_path"] = str_replace("%time%", $GLOBALS['wf_custom_upload_time'], $changable_data["file_path"]);
        return $changable_data;
    }
    add_filter('wfu_before_file_check', 'wfu_before_file_check_handler', 10, 2); 
}

额外注意事项

如果你需要保证同一个用户打开页面后,不管停留多久上传都用同一个时间戳,建议把时间戳存在用户Session或者前端表单隐藏字段中,上传时同步携带参数,避免页面长时间停留后PHP重新执行生成新的时间戳。

内容的提问来源于stack exchange,提问作者Elkelthen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 13:06:05