Adding new menu page to dashboard

I’m looking to use add_menu_page to add a new section to the WordPress dashboard. My only issue is where to put this code? I’ve looked around at several tutorials and frustratingly not one mentions where to add the code!

If someone could tell me:

Read More
  1. Where to put your add_menu_page code and
  2. Where to register the function passed as a parameter to the add_menu_page function

that would be greatly appreciated.

Related posts

Leave a Reply

2 comments

  1. Normally I wouldn’t answer a question that doesn’t have any code that you’ve already tried in, but it seems like this is a more abstract question so I’ll give a more abstract answer.

    ‘Hacking’ into WordPress is achieved by using hooks that are triggered when certain actions are executed by WordPress. When a hook is reached the system checks to see if there are any functions registered that are to be called at that point in the execution. Your menu page can be registered in the functions.php file of your theme or in a plugin file – it doesn’t really matter as long as you register it with the appropriate action hook.

    Example

    First we need a page for the menu item to link to (create this page anywhere, but ideally in your theme directory if you’re doing a theme or plugin directory if you’re doing a plugin). I called mine settings_page.php and put it in my theme directory.

    Then we’ve got your function to register your menu page (in functions.php if you’re doing a theme or in your main plugin file if you’re doing a plugin):

    function create_menu() {
        $settings_page = add_menu_page( 
            __("My Settings", EMU2_I18N_DOMAIN),
            __("My Settings", EMU2_I18N_DOMAIN),
            0,
            THEME_DIRECTORY.'/settings_page.php' 
            // obviously replacing THEME_DIRECTORY with your actual directory
        );
    }
    

    Then we register your menu page with the WordPress hook – in this case the ‘admin_menu’ hook (in the same file as the one you registered your function above in):

    add_action( 'admin_menu', 'create_menu' );
    

    Now you’re done. I’ve listed a couple of extra resource below in case you want to delve into anything a bit deeper, but I hope that helped lay a bit more groundwork as to what’s going on under the surface.

    Extra Resources

    Function reference for create_menu in WordPress codex

    Function reference for create_sub_menu in WordPress codex

    List of WordPress Hooks

    WordPress tutorial for writing a plugin