Question #1 – The above code will output 23123 twice, when visiting
plugin page and when not. How do I make it print the content of my
page only when page is the current screen? Basically:
http://localhost/wp-admin/admin.php?page=camden-vmtool
When you initialize the class, you are hooking the pageInit()
method into a hook that fires on all admin pages. You are then specifically calling that method in your add_menu_page()
arguments.
Honestly, I don’t understand this one:
Question #2 – How to preload only one page class based on currently
opened page? I will have around 4 pages, and It feels bad to load
classes at once, just to have the class instance initiated.
As to the first question, I don’t know what PageInit()
needs to do but given the limited information there is no need to instantiate the class beforehand. This works as is:
class VmSettingsPage {
private $options;
public function __construct()
{
add_action('admin_init', array($this, 'pageInit'));
}
public function pageInit() {
echo 23123;
}
}
// $settingsPage = new VmSettingsPage();
add_action('admin_menu', 'cvmAdminMenu');
function cvmAdminMenu() {
add_menu_page('VM Tool', 'VM Tool',
'manage_options', 'camden-vmtool', array('VmSettingsPage','pageInit'));
}
The class will be instantiated automatically. If you do need to instantiate the class then your callback should be different:
class VmSettingsPage {
private $options;
public function __construct()
{
// add_action('admin_init', array($this, 'pageInit'));
}
public function pageInit() {
echo 23123;
}
}
global $settingsPage;
$settingsPage = new VmSettingsPage();
add_action('admin_menu', 'cvmAdminMenu');
function cvmAdminMenu() {
global $settingsPage;
add_menu_page('VM Tool', 'VM Tool',
'manage_options', 'camden-vmtool', array($settingsPage,'pageInit'));
}
If you do that, then you can’t use admin_init
but there is no apparent reason to use that admin_init
hook at all anyway.
I would further suggest that you encapsulate everything into your class:
class VmSettingsPage {
private $options;
public function __construct()
{
// add_action('admin_init', array($this, 'pageInit'));
add_action('admin_menu', array($this,'cvmAdminMenu'));
}
function cvmAdminMenu() {
add_menu_page('VM Tool', 'VM Tool',
'manage_options', 'camden-vmtool', array($this,'pageInit'));
}
public function pageInit() {
echo 23123;
}
}
$settingsPage = new VmSettingsPage();