2012-11-12 42 views
5

我想寫一個插件與多個文件,我敢肯定我做過之前沒有 一個問題,但現在我有問題的主題。在wordpress插件中使用多個文件 - 調用未定義的函數add_action()

在我包括文件名的主要插件文件 - YDP-includes.php, YDP-includes.php我包括了所有我想是這樣的文件裏面:

<?php 
include(dirname(__FILE__) .'/1.php'); 
include(dirname(__FILE__) .'/2.php'); 
include(dirname(__FILE__) .'/3.php'); 
include(dirname(__FILE__) .'/4.php'); 
?> 

,但我得到:致命的錯誤:調用未定義的函數add_action() 該文件包括,但由於我目前無法看到的原因wordpress 沒有看到它們作爲一個插件包和每個wordpress函數被忽略。

是否有另一種開發多文件wordpress插件的最佳實踐方式? 我做錯了什麼?

感謝

+0

這是更好地創建具有所有類功能,如果可能的話,或幾個具有特定功能的類別。 ¿是否有任何理由使用包含的函數包含的文件?根據這些包含文件的位置,WP可能無法將它們識別爲插件的一部分。 –

回答

5

在PHP includestatement not a function

所以應該

<?php 
include dirname(__FILE__) .'/1.php'; 
include dirname(__FILE__) .'/2.php'; 
include dirname(__FILE__) .'/3.php'; 
include dirname(__FILE__) .'/4.php'; 
?> 

,或者是完美

<?php 
require_once dirname(__FILE__) .'/1.php'; 
require_once dirname(__FILE__) .'/2.php'; 
require_once dirname(__FILE__) .'/3.php'; 
require_once dirname(__FILE__) .'/4.php'; 
?> 
+1

-1是語義的,兩種包含文件的方法都是有效的。 +1用於推薦require_once。 :] –

1

使用plugin_dir_path(__FILE__);讓你的插件文件。使用下面的代碼引用:

$dir = plugin_dir_path(__FILE__); 

require_once($dir.'1.php'); 

require_once($dir.'2.php'); 

require_once($dir.'3.php'); 

require_once($dir.'4.php'); 
3

根據錯誤消息,它聽起來像你試圖直接訪問插件文件,這是不正確的。 WordPress的使用前端控制器設計模式,這意味着你會希望有你的文件是這樣的:

my-plugin-folder/my-plugin-name.php 
my-plugin-folder/includes/ydp-includes.php 
my-plugin-folder/includes/ydp-database.php 

裏面的我的插件 - name.php的:

//Get the absolute path of the directory that contains the file, with trailing slash. 
define('MY_PLUGIN_PATH', plugin_dir_path(__FILE__)); 
//This is important, otherwise we'll get the path of a subdirectory 
require_once MY_PLUGIN_PATH . 'includes/ydb-includes.php'; 
require_once MY_PLUGIN_PATH . 'includes/ydb-database.php'; 
//Now it's time time hook into the WordPress API ;-) 
add_action('admin_menu', function() { 
    add_management_page('My plugin Title', 'Menu Title', 'edit_others_posts', 'my_menu_slug', 'my_plugin_menu_page_content' 
}); 
//Php 5.3+ Required for anonymous functions. If using 5.2, create a named function or class method 

function my_plugin_menu_page_content() { 
    //Page content here 
} 

這將添加一個WordPress管理菜單項,並加載所需的文件。您也可以要求包含文件的內多個文件現在,使用常量MY_PLUGIN_PATH

參見:

add_menu_page plugin_dir_path()

相關問題