Adding Administration Menus

来自WordPress中文文档
Zhuozuran讨论 | 贡献2009年3月14日 (六) 09:23的版本 (1个修订)
跳转至: 导航搜索

Introduction

Many plugins give their users options or settings, which allow the users a way to customize how the plugin is used. As a plugin author, you have several choices in how to set this up. One way is to have the user edit information in the plugin's PHP file, but this makes many users uncomfortable (to say the least). So, a better way is usually to create administration screens that let the plugin user set options in a more familiar manner.

This article explains how to add custom administration screens to WordPress in a plugin. It assumes you are already familiar with the basics of Writing a Plugin and the Plugin API of Actions and Filters.

Every Plot Needs a Hook

To add an admin menu, you must do three things:

  1. Create a function which contains the menu-building code
  2. Register the above function using the admin_menu action hook
  3. Create the HTML output for the page displayed when the menu item is clicked

Code should be added in the main plugin php file or a separate php include.

The second step is often overlooked by new plugin developers. You cannot simply call the menu code described below; you must put it inside a function and then register the function.

A very simple example of the above three steps: pre ?php add_action('admin_menu', 'my_plugin_menu');

function my_plugin_menu() {

 add_options_page('My Plugin Options', 'My Plugin', 8, __FILE__, 'my_plugin_options');

}

function my_plugin_options() {

 echo 'div class=wrap';
 echo 'pHere is where the form would go if I actually had options./p';
 echo '/div';

} ? /pre

As you can see, we have a function, ttmy_plugin_menu/tt, which adds a new item to the Admin menu (via the ttadd_options_page/tt function, described in the next section--more complicated multiple menu items can be added, as seen below). Then, we invoke the Wordpress hook which registers this function. Without that, a PHP error for undefined function will be thrown when you attempt to activate the plugin. Lastly, we create a function which contains the actual page to be displayed (and PHP code to be processed) when someone clicks the menu item.

The actual processes for the last two of these three steps are described in the sections below. But do not forget that you must enclose them in functions, and invoke that ttadmin_menu/tt hook to get the whole process started!

Menus and Submenus

Before creating custom administration screens you must figure out where in the WordPress administration menu system they belong. Most plugins add their screens as submenus underneath the existing WordPress top-level menus. Here is a guide to what belongs in which top-level menu:

Settings
Displays plugin options that only administrators should view (also see Creating Settings Pages).
Manage
Displays management controls for links, posts, categories, images, etc.
Plugins
Displays controls dealing with plugin management, not configuration options for a plugin itself.
Presentation
Displays controls for manipulation of theme/style files, sidebars, etc.
Write
Displays tools for writing content (posts and pages).
Users
Displays controls for user management.

If your plugin introduces an entirely new concept or feature to WordPress, and needs many screens to do it, another option is to create a new top-level menu for your plugin. This should only be considered if you really need multiple, related screens to make WordPress do something it was not originally designed to do. Examples might include management of image galleries, database administration, or conference management.

With the Custom Admin Menu plugin, users now also have the ability to decide for themselves if they want your plugin to occupy a top-level menu item or not -- you may want to make clear to users that they have that option, particularly if you've decided to create a top-level menu item.

Admin Menu Functions

Now that you have decided where to add your menu/submenu, the next step is to tell WordPress about your new pages. All of this will take place in a function you have registered as an tt'admin_menu'/tt action (see example at bottom of this section).

Top-Level menu

If for some reason you have decided that your plugin really needs a brand-new top-level menu, the first thing you'll need to do is to create one. Otherwise, skip to Sub-Menus below.

To add a new top-level menu, you'll use the ttadd_menu_page/tt function:

add_menu_page(page_title, menu_title, access_level/capability, file, [function], [icon_url]);

Parameter values:

page_title
Text that will go into the HTML page title for the page when the menu is active.
menu_title
The on-screen name text for the menu.
access_level/capability
The minimum user level or the capability required to display and use this menu page.
file
The PHP file that handles the display of the menu page content.
function
The function that displays the page content for the menu page.

Technically, the function parameter is optional, but if it is not supplied, then WordPress will basically assume that including the PHP file will generate the administration screen, without calling a function. Most plugin authors choose to put the page-generating code in a function within their main plugin file.

icon_url
This only works in WordPress 2.7. It's places a custom icon in the menu for you.

Sub-Menus

Once you have a top-level menu defined, or have chosen to use an existing WordPress top-level menu, you are ready to define one or more sub-menu pages using the ttadd_submenu_page/tt function. Make sure to add the submenu pages in the order you want them displayed.

add_submenu_page(parent, page_title, menu_title, access_level/capability, file, [function]);

Parameter values:

parent
The filename of the core WordPress admin file that supplies the top-level menu in which you want to insert your submenu, or your plugin file if this submenu is going into a custom top-level menu.

Commonly-used examples:

  1. For Write: add_submenu_page('post-new.php',...)
  2. For Manage: add_submenu_page('edit.php',...)
  3. For Design: add_submenu_page('themes.php',...)
  4. For Comments: add_submenu_page('edit-comments.php',...)
  5. For Settings: add_submenu_page('options-general.php',...)
  6. For Plugins: add_submenu_page('plugins.php',...)
  7. For Users: add_submenu_page('users.php',...)
page_title
Text that will go into the HTML page title for the page when the submenu is active.
menu_title
The on-screen name text for the submenu.
access_level/capability
The minimum user level or the capability required to display and use this submenu page.
file
For existing WordPress menus, the PHP file that handles the display of the menu page content. For submenus of a custom top-level menu, a unique identifier for this sub-menu page.

In situations where a plugin is creating it's own top-level menu, the first submenu will normally have the same link title as the top-level menu and hence the link will be duplicated. The duplicate link title can be avoided by calling the add_submenu_page function the first time with the parent and file parameters being given the same value.

function
The function that displays the page content for the menu page.

Technically, as in the ttadd_menu_page/tt function, the function parameter is optional, but if it is not supplied, then WordPress will basically assume that including the PHP file will generate the administration screen, without calling a function. Most plugin authors choose to put the page-generating code in a function within their main plugin file.

Here's a quick example, illustrating how to insert a top-level menu page and a sub-menu page, where the title on the sub-menu page is different from the top-level page. In this example, 'my_magic_function' is the name of the function that displays the first sub-menu page: pre add_menu_page('Page title', 'Top-level menu title', 8, __FILE__, 'my_magic_function'); add_submenu_page(__FILE__, 'Page title', 'Sub-menu title', 8, __FILE__, 'my_magic_function'); /pre

Since most submenus go into WordPress's Options, Management, or Presentation menus, WordPress supplies three wrapper functions that make adding a submenu to those pages easier:

For the Options top-level menu (see Creating Options Pages for more on this)
add_options_page(page_title, menu_title, access_level/capability, file, [function]);
For Management
add_management_page(page_title, menu_title, access_level/capability, file, [function]);
For Presentation
add_theme_page( page_title, menu_title, access_level/capability, file, [function]);

Inserting the Pages

Here is an example of a WordPress plugin that inserts new menus into various places:

pre ?php /* Plugin Name: Menu Test Plugin URI: http://wordpress.org Description: Menu Test Author: Nobody Author URI: http://example.com

  • /

// Hook for adding admin menus add_action('admin_menu', 'mt_add_pages');

// action function for above hook function mt_add_pages() {

   // Add a new submenu under Options:
   add_options_page('Test Options', 'Test Options', 8, 'testoptions', 'mt_options_page');
   // Add a new submenu under Manage:
   add_management_page('Test Manage', 'Test Manage', 8, 'testmanage', 'mt_manage_page');
   // Add a new top-level menu (ill-advised):
   add_menu_page('Test Toplevel', 'Test Toplevel', 8, __FILE__, 'mt_toplevel_page');
   // Add a submenu to the custom top-level menu:
   add_submenu_page(__FILE__, 'Test Sublevel', 'Test Sublevel', 8, 'sub-page', 'mt_sublevel_page');
   // Add a second submenu to the custom top-level menu:
   add_submenu_page(__FILE__, 'Test Sublevel 2', 'Test Sublevel 2', 8, 'sub-page2', 'mt_sublevel_page2');

}

// mt_options_page() displays the page content for the Test Options submenu function mt_options_page() {

   echo h2Test Options/h2;

}

// mt_manage_page() displays the page content for the Test Manage submenu function mt_manage_page() {

   echo h2Test Manage/h2;

}

// mt_toplevel_page() displays the page content for the custom Test Toplevel menu function mt_toplevel_page() {

   echo h2Test Toplevel/h2;

}

// mt_sublevel_page() displays the page content for the first submenu // of the custom Test Toplevel menu function mt_sublevel_page() {

   echo h2Test Sublevel/h2;

}

// mt_sublevel_page2() displays the page content for the second submenu // of the custom Test Toplevel menu function mt_sublevel_page2() {

   echo h2Test Sublevel 2/h2;

}

? /pre

Sample Menu Page

The example above contains several dummy functions, such as ttmt_options_page/tt, as placeholders for actual page content. We need to turn them into real menu pages. So, let's assume that our plugin has an option called mt_favorite_food, and that we want to allow the site owner to type in his/her favorite food on the plugin's Option page. The ttmt_options_page/tt function will need to put a data entry form on the screen to enable this, and also process the entered data. Here is a function that does this:

pre

// mt_options_page() displays the page content for the Test Options submenu function mt_options_page() {

   // variables for the field and option names 
   $opt_name = 'mt_favorite_food';
   $hidden_field_name = 'mt_submit_hidden';
   $data_field_name = 'mt_favorite_food';
   // Read in existing option value from database
   $opt_val = get_option( $opt_name );
   // See if the user has posted us some information
   // If they did, this hidden field will be set to 'Y'
   if( $_POST[ $hidden_field_name ] == 'Y' ) {
       // Read their posted value
       $opt_val = $_POST[ $data_field_name ];
       // Save the posted value in the database
       update_option( $opt_name, $opt_val );
       // Put an options updated message on the screen

? div class=updatedpstrong?php _e('Options saved.', 'mt_trans_domain' ); ?/strong/p/div ?php

   }
   // Now display the options editing screen
   echo 'div class=wrap';
   // header
   echo h2 . __( 'Menu Test Plugin Options', 'mt_trans_domain' ) . /h2;
   // options form
   
   ?

form name=form1 method=post action=?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ? input type=hidden name=?php echo $hidden_field_name; ? value=Y

p?php _e(Favorite Color:, 'mt_trans_domain' ); ? input type=text name=?php echo $data_field_name; ? value=?php echo $opt_val; ? size=20 /phr /

p class=submit input type=submit name=Submit value=?php _e('Update Options', 'mt_trans_domain' ) ? / /p

/form /div

?php

} /pre

A few notes:

  • The WordPress administration functions take care of validating the user, so you don't have to worry about it in your function.
  • The function example above has been internationalized -- see the Internationalization section of Writing a Plugin for more information
  • The function processes any entered data before putting the data entry form on the screen, so that the new values will be shown in the form (rather than the values from the database).
  • You don't have to worry about this working the first time, because the WordPress ttupdate_option/tt function will automatically add an option to the database if it doesn't already exist.
  • These admin-menu-adding procedures are parsed every single time you navigate to a page in Admin. So if you are writing a plugin which has no options page, but add one later, you can just add it using the instructions above and re-upload, and tweak until you're happy with it. In other words, menus are not permanently added or put into a database upon activating a plugin. They're parsed on the fly, so you can add or subtract menu items at will, re-upload, and the change will be reflected right away.

Resources