Читать книгу Professional WordPress Plugin Development - Brad Williams - Страница 72

Creating a Top‐Level Menu

Оглавление

The first menu method for your plugin to explore in WordPress is a new top‐level menu, which is added to the Dashboard menu list. For example, Settings is a top‐level menu. A top‐level menu is common practice for any plugin that needs multiple option pages. To register a top‐level menu, you use the add_menu_page() function.

<?php add_menu_page( page_title, menu_title, capability, menu_slug, function, icon_url, position ); ?>

The add_menu_page() function accepts the following parameters:

 page_title: Title of the page as shown in the <title> tags.

 menu_title: Name of your menu displayed on the Dashboard.

 capability: Minimum capability required to view the menu.

 menu_slug: Slug name to refer to the menu; should be a unique name.

 function: Function to be called to display the page content for the item.

 icon_url: URL to a custom image to use as the menu icon. Also supports the dashicons helper class to use a font icon (e.g. dashicons‐chart‐pie).

 position: Location in the menu order where it should appear.

Now create a new menu for your plugin to see the menu process in action. Use the admin_menu action hook to trigger your menu code. This is the appropriate hook to use whenever you create menus and submenus in your plugins.

<?php add_action( 'admin_menu', 'pdev_create_menu' ); function pdev_create_menu() { //create custom top-level menu add_menu_page( 'PDEV Settings Page', 'PDEV Settings', 'manage_options', 'pdev-options', 'pdev_settings_page', 'dashicons-smiley', 99 ); } ?>

As you can see, the admin_menu action hook calls your custom pdev_create_menu() function. Next you need to call the add_menu_page() function to register the custom menu in WordPress. Set the name of your menu to PDEV Settings, require that the user has manage_options capabilities (that is, is an administrator), and set the callback function to pdev_settings_page(). You also set the menu icon to use the built‐in smiley dashicon (covered in detail later in this chapter). The final parameter is the menu position, which defines where the menu will appear within the WordPress Dashboard's left menu.

The result is a custom registered menu as shown in Figure 3‐1.


FIGURE 3‐1: Custom registered menu

NOTE Menus are a common feature in WordPress plugins and are generally expected by users. It's a good idea to mention where your plugin settings can be found in the plugin description and documentation.

Professional WordPress Plugin Development

Подняться наверх