Using Object-Oriented Approach in Building WordPress Admin Menus

The code bellow will output the same way it’s outputted in Procedural Approach.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
add_action('admin_menu', array('Ad_Admin', 'cvf_register_site_options') );

class My_Admin {
   
    public function __construct() {
       
    }
   
    public static function cvf_register_site_options() {
        add_submenu_page( 'tools.php', 'Custom Submenu', 'Custom Submenu', 'administrator', 'custom-submenu', 'My_Admin::custom_submenu' );
    }
   
    public static function custom_submenu(){
        echo 'Test';
    }
   
}

Notice how we use My_Admin::custom_submenu to access the static function custom_submenu(). It’s important we declare our outputting function as static so we could access it using the scope resolution operator.