2011-06-28 67 views
7

我爲我的WordPress網站編寫了一個自定義插件,該插件依賴於從插件文件夾中的xml數據文件讀取/寫入。當我測試這個用於文件讀/寫的標準PHP代碼時,它將允許我創建/寫入位於wp-admin/level的文件,但不能在插件文件夾中創建文件,儘管它可以從兩者讀取。從我的WordPress插件寫入文件

$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的服務器上的插件。什麼是正確的方法?

謝謝,

回答

10

如果要寫入文件,請勿通過HTTP訪問它。因爲讀取和寫入速度更快,而且是直接訪問文件的最直接方法,所以可以直接訪問它。

要獲得基本的插件目錄路徑,使用WP_PLUGIN_DIR常數:

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

這將防止您使用HTTP不應使用在所有的,因爲性能的原因和HTTP不支持寫作。但最重要的是,因爲它是您可以訪問的服務器上的文件,所以可以直接訪問它。

+0

@hakre任何想法,如果類似的東西存在的主題?像'WP_THEME_DIR'> – Blowsie

+2

@Blowsie:沒有這樣的常量,但類似的東西。看到這裏的「大圖片」:http://codex.wordpress.org/Determining_Plugin_and_Content_Directories – hakre