I would like to understand why I cannot use [ $this, ‘function’ ] within it’s own class.
This works:
init.php
if ( is_admin() )
{
require ( dirname ( __FILE__ ) . '/inc/admin/Admin.php' );
add_action('admin_menu', ['MangoAdmin', 'adminMenu'] );
}
/inc/admin/Admin.php – Version 1 (working)
<?php namespace Mango;
class Admin
{
public function adminMenu()
{
//this is the main item for the menu
add_menu_page(
'Mango Settings', //page title
'Mango Settings', //menu title
'manage_options', //capabilities
'mango-settings', //menu slug
[ 'MangoAdmin', 'settingsPage' ] // LOOK HERE *******
);
}
public function settingsPage()
{
echo 'This is a test';
}
}
/inc/admin/Admin.php – Version 2 (not working)
<?php namespace Mango;
class Admin
{
public function adminMenu()
{
//this is the main item for the menu
add_menu_page(
'Mango Settings', //page title
'Mango Settings', //menu title
'manage_options', //capabilities
'mango-settings', //menu slug
[ $this, 'settingsPage' ] // LOOK HERE *******
);
}
public function settingsPage()
{
echo 'This is a test';
}
}
Error Message: Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in /.../wp-includes/plugin.php on line 429
I don’t really understand why I cannot register [ $this, 'settingsPage' ]
with the add_menu_page hook. Surely the working version 1 is needlesly creating a 2nd copy of the MangoAdmin class?
Can anybody shed some light on this for me please?
Maybe a little late for an answer, but it probably would help others too;
If the function is a member of a class within the plugin it should be
referenced as array( $this, ‘function_name’ )
http://codex.wordpress.org/Function_Reference/add_menu_page