WordPress add_menu_page() OOP & how to load scripts/styles on menu page


Example

<?php
/*
 *  Plugin Name: Custom Admin Menu
 */

class SO_WP_Menu {

    private $plugin_url;
    
    public function __construct() {
        $this->plugin_url = plugins_url( '/', __FILE__ );
        add_action( 'plugins_loaded', array( $this, 'init' ) );
    }

    public function init() {
        add_action( 'admin_menu', array( $this, 'add_menu' ) );
    }

    public function add_menu() {
        $hook = add_menu_page(
            'My Menu',                 // Title, html meta tag
            '<span style="color:#e57300;">My Menu</span>', // Menu title, hardcoded style
            'edit_pages',              // capability
            'dummy-page-slug',         // URL
            array( $this, 'content' ), // output
            null,                      // icon, uses default
            1                          // position, showing on top of all others
        );
        add_action( "admin_print_scripts-$hook", array( $this, 'scripts' ) );
        add_action( "admin_print_styles-$hook", array( $this, 'styles' ) );
    }

    public function content() {
        ?>
            <div id="icon-post" class="icon32"></div>
            <h2>Dummy Page</h2>
            <p> Lorem ipsum</p>
        <?php
    }

    # Printing directly, could be wp_enqueue_script
    public function scripts() {
        ?><script>alert('My page');</script><?php
    }

    # Enqueing from a CSS file on plugin directory
    public function styles() {
        wp_enqueue_style( 'my-menu', $this->plugin_url . 'my-menu.css' );
    }
}

new SO_WP_Menu();

What's important to note in this example is that, when using add_menu_page(), it returns a hook that can be used to target our exact page and load Styles and Scripts there.
A common mistake is to enqueue without targeting and that spills scripts and styles all over /wp-admin.
Using OOP we can store common variables to be used among internal methods.