Adding an admin page – OOP approach not working

I have a parent class, which contains the following:

use app\My_Dashboard;

class My_Class {
    public function __construct() {
        add_action('admin_menu', array($this, 'setup_dashboard_page'));
    }

    public function setup_dashboard_page() {
        My_Dashboard::add_dashboard_page();
    }

}

And the class which has the admin page functions:

class My_Dashboard {
    public static function add_dashboard_page() {
        add_menu_page('My Settings', 'My Settings', 'my-settings', array($this, 'dashboard_page_cb'));
    }

    public function dashboard_page_cb() {
        //The markup
    }
}

This approach doesn’t work, and I cannot see my admin menu item and page added. The second approach I tried:

use app\My_Dashboard;

class My_Class {
    public function __construct() {
        add_action('admin_menu', array($this, 'setup_dashboard_page'));
    }

    public function setup_dashboard_page() {
        //Not very sure of the syntax, bad at OOP
        add_menu_page('My Settings', 'My Settings', 'my-settings', 'My_Dashboard::dashboard_page_cb');
    }
}

How do I get it to work? My idea is to separate all the dashboard related stuff to the other class.

Update:
The first approach worked, and the menu item is added. But the callback function that outputs the page markup doesn’t seem to work. I checked for typos but everything seems okay.

3 Answers
3

I hate OOP mixed in the functional structure of wordpress (here come the downvotes…..). If you use OOP just for name spacing then just use the name spacing feature of PHP, putting function in a class is just a very small part of what OOP should be.

Anyway, your problems is that a there are only two way to refere to an class method, either when it is associated with a specific object or if it is static in the class (basically associated with the class but not with the objects). In your code you try to treat an object bound function as if it is a static one (I am sure that if you will check your error log you will see some relevant error). There are two possible way to fix it
1. Make the relevant functions static and use the syntax in your second variation
2. use a singleton patter, instantiate an object of the dashboard class, keep it as a global and use it instead of the class name in your first variation. instead of

public function setup_dashboard_page() {
    My_Dashboard::add_dashboard_page();
}

do

global $dashboard;
$dashboard = new my_dashboard()
.....
public function setup_dashboard_page() {
   global $dashboard;
    $dashboard->add_dashboard_page();
}

And always debug code with full error reporting and fix all errors and notices 😉

Leave a Comment