我为我的 WordPress 网站编写了一个自定义插件,该插件依赖于从插件文件夹中的 xml 数据文件读取/写入。当我测试这个用于文件读/写的标准 PHP 代码时,它会让我创建/写入位于 wp-admin/级别的文件,但不是插件文件夹中的文件,尽管它可以从两者读取。
$file = 'test.xml'; (Can write to this file)
$file = plugins_url()."/my-plugin/test.xml"; (Can read but not write to this file)
// Open the file to get existing content
$current = file_get_contents($file);
echo $current;
// Append a new person to the file
$current .= "<person>John Smith</person>\n";
// Write the contents back to the file
file_put_contents($file, $current);
我收到以下调试错误:
Warning: file_put_contents(http://localhost/wp_mysite/wp-content/plugins/my-plugin/test.xml) [function.file-put-contents]: failed to open stream: HTTP wrapper does not support writeable connections in /Applications/MAMP/htdocs/wp_mysite/wp-content/plugins/my-plugin/my-plugin.php on line 53
我目前正在本地 MAMP 服务器上运行它,但想要一个能让我在任何 WordPress 服务器上打包和发布插件的解决方案。什么是正确的方法?
谢谢-
最佳答案
如果您想写入文件,请不要通过 HTTP 访问它。直接访问它而不是读取和写入,因为它是访问文件的更快和最直接的方法。
要获取基本插件目录路径,请使用 WP_PLUGIN_DIR
常量:
$file = 'test.xml'; // (Can write to this file)
$file = WP_PLUGIN_DIR."/my-plugin/test.xml";
// ^^^^^^^^^^^^^
这将阻止您使用 HTTP,由于性能原因和 HTTP 不支持写入,根本不应该使用 HTTP。但最重要的是,由于它是您有权访问的服务器上的一个文件,因此请直接访问它。
关于php - 从我的 WordPress 插件写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6505700/