So, I’ve been staring at this problem for a few days now. I am attempting to push my skills further in PHP development, and decided to tackle a WP plugin with an OOP approach. I know that WP isn’t necessarily the best choice for this, but I love a good challenge.
I am writing a Helper class, as I intend to use some functions fairly regularly, but I am running into a little bit of an issue.
Helper Class
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']
);
} );
}
Helper Class Usage
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',
]);
}
}
Current Output
Things I’ve tried
- Putting the array into a foreach loop. Not working because, will either return the first one twice or return all three again.
- Original route was as a pass by reference type of thing. Passing the variables from the function and storing them in global vars within the class. Still not working due to same issue as described
My current thoughts are that it is something to do with the use of the add_action and an anonymous function alongside the fact that the add_action gets called everytime the helper function is called.
Hopefully someone has some sort of idea of a solution for this, and hopefully I have been clear enough in my issue.
Thanks 🙂