WordPress中plugin_dir_path为何会截断末尾目录?
plugin_dir_path 为何截断末尾的“src”目录?
调试代码
error_log('---> plugin_dir_path ' . plugin_dir_path('/includes/phpspreadsheet-3.7.0/src/')); error_log('---> plugin_dir_path 2 ' . plugin_dir_path('/includes/phpspreadsheet-3.7.0/src/src'));
日志输出
[07-Jan-2025 11:15:00 UTC] ---> plugin_dir_path /includes/phpspreadsheet-3.7.0/ [07-Jan-2025 11:15:00 UTC] ---> plugin_dir_path 2 /includes/phpspreadsheet-3.7.0/src/
原因解析
plugin_dir_path 是 WordPress 专为获取插件文件所在目录设计的函数,核心逻辑是:自动将传入路径的最后一段判定为「文件名」,返回该文件的父目录路径——不管最后一段实际是文件还是目录。
具体到你的调用:
- 第一个调用:传入的
/includes/phpspreadsheet-3.7.0/src/会被去掉末尾的目录分隔符,变成/includes/phpspreadsheet-3.7.0/src,函数将最后一段src判定为文件名,因此返回其父目录/includes/phpspreadsheet-3.7.0/ - 第二个调用:传入的
/includes/phpspreadsheet-3.7.0/src/src最后一段是src,同样被判定为文件名,返回其父目录/includes/phpspreadsheet-3.7.0/src/
解决方法
如果只是要获取指定目录的完整路径,不要用 plugin_dir_path,改用 WordPress 的 trailingslashit() 函数(确保路径末尾带目录分隔符),或者直接用 PHP 原生的 realpath():
// 方式1:用trailingslashit获取带末尾分隔符的目录路径 $src_dir = trailingslashit('/includes/phpspreadsheet-3.7.0/src/'); error_log('---> src_dir ' . $src_dir); // 输出 /includes/phpspreadsheet-3.7.0/src/ // 方式2:用realpath获取标准化的绝对路径 $src_dir = realpath('/includes/phpspreadsheet-3.7.0/src/') . DIRECTORY_SEPARATOR; error_log('---> src_dir ' . $src_dir);
内容的提问来源于stack exchange,提问作者xman
相关产品推荐
相关产品推荐

