开发者

Writing to a file from my WordPress plugin

I've written a custom plugin for my WordPress site that relies on reading/writing from an xml data file within the plugin folder. When I test this standard PHP code for file reading/writing, it will let me c开发者_C百科reate/write to files located at the wp-admin/ level, but not files within the plugin folder, although it can read from both.

$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);

I get the following debug error:

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

I'm currently running this off a local MAMP server, but want a solution that will let me package and publish the plugin on any WordPress server. What is the right approach?

Thanks-


Don't access it via HTTP if you want to write to the file. Access it directly instead for both reading and writing as it's much faster and the most direct method to access a file.

To get the base plugin directory path, use the WP_PLUGIN_DIR constant:

$file = 'test.xml';  // (Can write to this file)
$file = WP_PLUGIN_DIR."/my-plugin/test.xml"; 
//      ^^^^^^^^^^^^^

This will prevent you from making use of HTTP which should not be used at all because of performance reasons and because HTTP does not support writing. But foremost, as it's a file on the server you have access to, access it directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜