我已经盯着这个问题看了几天了。我试图进一步提高我在PHP开发方面的技能,并决定使用面向对象的方法来处理WP插件。我知道WP不一定是最好的选择,但我喜欢一个好的挑战。
我正在编写一个Helper类,因为我打算相当经常地使用一些函数,但我遇到了一些小问题。
Class Helper implements HelperInterface
{
/**
* Default Options for making an admin page
*
* @var array
*/
public $default_options = [
'slug' => '',
'title' => '',
'page_title' => '',
'parent' => null,
'id' => '',
'capability' => 'update_core',
'icon' => 'dashicons-admin-generic',
'position' => null,
'file_name' => null,
'desc' => '',
];
/**
* Store options passed in by user.
*
* @var array
*/
public $options = [];
public $parent_id;
public $settings_id;
/**
* Stores the media type for a stylesheet
*
* @var string
*/
public $media_type;
public function __construct( )
{
}
public function add_new_page( $opt )
{
$this->options = array_merge( $this->default_options, $opt );
add_action( 'admin_menu', function() {
add_menu_page(
$this->options['page_title'],
$this->options['title'],
$this->options['capability'],
$this->options['slug'],
array($this, display_page_template),
$this->options['icon'],
$this->options['position']
);
} );
}Class GoogleMaps
{
protected $helper;
public function __construct()
{
$this->helper = new Helper;
$this->helper->add_new_page([
'slug' => 'google-maps',
'title' => 'EdsGoogleMaps',
'page_title' => 'EdsGoogleMaps',
'capability' => 'update_core',
'icon' => 'dashicons-admin-generic',
'position' => null,
'file_name' => 'GoogleMapsHome.php',
]);
$this->helper->add_new_page([
'slug' => 'google-maps-2',
'title' => 'EdsGoogleMaps2',
'page_title' => 'EdsGoogleMaps2',
'capability' => 'update_core',
'icon' => 'dashicons-admin-generic',
'position' => null,
'file_name' => 'GoogleMapsHome.php',
]);
$this->helper->add_new_page([
'slug' => 'google-maps-3',
'title' => 'EdsGoogleMaps3',
'page_title' => 'EdsGoogleMaps3',
'capability' => 'update_core',
'icon' => 'dashicons-admin-generic',
'position' => null,
'file_name' => 'GoogleMapsHome.php',
]);
}
}
我目前的想法是,这与add_action和匿名函数的使用有关,而且每次调用助手函数时都会调用add_action。
希望有人对此有某种解决方案,希望我在我的问题上已经足够清楚了。
谢谢:)
发布于 2018-04-01 19:53:58
对匿名函数的调用是在执行所有add_new_page之后完成的。然后,您需要存储所有元素来创建菜单项。
尝试像这样修改类帮助程序
public function __construct() // method to modify
{
add_action("admin_menu", [$this, "add_admin_menu_items"]);
}
public function add_new_page( $opt ) // method to modify
{
$element = array_merge( $this->default_options, $opt );
$this->options[] = $element;
}
public function add_admin_menu_items() // method to create
{
$helper = $this;
foreach ($this->options as $element) {
add_menu_page(
$element['page_title'],
$element['title'],
$element['capability'],
$element['slug'],
function () use ($helper, $element) {
$helper->display_page_template($element);
},
$element['icon'],
$element['position']
);
}
}
public function display_page_template($itemDatas)
{
?>https://wordpress.stackexchange.com/questions/299551
复制相似问题