Return value of add_menu_page

I’ve read this on codex and seem some themes use it but never understood how it worked.

(string) $hookname used internally to track menu page callbacks for outputting the page inside the global $menu array

Read More

I can’t seem to understand the codex’s explanation. Can some one enlighten me on how can we use the return value and what are the uses of it?

Related posts

Leave a Reply

2 comments

  1. One important use is enqueue script / style only on specific plugin/admin pages.

    <?php
        add_action('init', 'my_plugin_admin_page');
    
        function my_plugin_admin_page()
        {
            //create the menu page
            $hook = add_menu_page(....);
    
            //use the hook for this page for enqueuing
            add_action('admin_print_styles-' . $hook, 'my_plugin_admin_styles');
        }
    
        function my_plugin_admin_styles()
        {
            //enqueue the style/script here
        }
    ?>
    

    This is one use I know.

  2. Hope code is self-explanatory.

    // Add a new submenu page and also add a load handler for it to process POSTs
    ($hook_name = add_submenu_page(
        'plugins.php', // Under plugins menu
        'Title',
        'Menu',
        'activate_plugins', // Administrators
        'slug',
        function(){ // Visual is here ?>
            <div class="wrap">
                <h2>Sub-Page Title</h2>
                <!-- Subpage visual output comes here -->
            </div>
    <?php })) and (add_action("load-{$hook_name}", function(){ // Hook the load here
        if(!strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')){
            $_POST =  stripslashes_deep($_POST); // Fix this WP BS security joke
            // Handle a POST request
            // ... Do stuff with $_POST
        }elseif(!strcasecmp($_SERVER['REQUEST_METHOD'], 'GET')){
            // Handle a GET (normal) request
            // ... Usually not needed
        }
    }));
    

    Have fun!