問題描述
情況:我正在開發一個外掛,我正在開發一個類,一切正常,直到遇到這種情況。我想讓事情有點清潔,並嘗試這個..
class MyPlugin {
function __construct() {
add_action('admin_menu', array(&$this, 'myplugin_create_menus');
}
//I don't want to write a function for every options page I create
//so I prefer to just load the content from an external file.
function load_view($filename) {
$view = require(dirname(__FILE__).'/views/'.$filename.'.php');
return $view;
}
//Here is where the problem comes
function myplugin_create_menus() {
add_menu_page( 'Plugin name',
'Plugin name',
'manage_options',
'my-plugin-settings',
array(&$this, 'load_view') // Where do I specify the value of $filename??
);
}
}#end of class
我已經嘗試了一堆不同的選項,但沒有任何作用,也許我在前面,但我看不到它。
當然這是一個 re-creation,我已經把所有的功能都放在前面了,而且並不完全符合我在這裡所寫的內容,但是希望你能得到我的要求。
提前致謝。
P.D .: 如果你想看到原始的原始碼,我很樂意貼上它並給你連結。
最佳解決方案
您不能將引數傳遞給回撥函式。 add_menu_page()將其新增為操作處理程序,admin.php 將觸發該操作,而不會有任何引數。
我看到這個問題的兩個簡單的解決方案。一個是將所有檔名儲存在你的類中的陣列中,由鉤子名稱索引。然後,您可以使用它來查詢需要載入的檔案 (您還可以在此陣列中儲存其他資料) 。
class WPSE16415_Plugin
{
protected $views = array();
function load_view() {
// current_filter() also returns the current action
$current_views = $this->views[current_filter()];
include(dirname(__FILE__).'/views/'.$current_views.'.php');
}
function myplugin_create_menus() {
$view_hook_name = add_menu_page( 'Plugin name',
'Plugin name',
'manage_options',
'my-plugin-settings',
array(&$this, 'load_view'),
);
$this->views[$view_hook_name] = 'options';
}
}
另一個是跳過回撥引數,所以 WordPress 將包括由 slug 名稱本身指示的檔案,正如 Brady 在他的回答中所說。
次佳解決方案
您可以隨時使用匿名函式 (或閉包) 。一些事情影響:
add_menu_page( $page, $menu, $capability, $slug, function() { print_my_admin_page($with_args); }, $icon, $position);
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。