wordpress 菜单_WordPress中的管理菜单

wordpress 菜单

The administration system in WordPress works well enough at first glance. The built-in menu functions take care of a lot of the issues such as adding and removing menu items, but you may want to learn more about how WordPress handles its menus internally to leverage more control. The example below will show how you can implement a plugin which enables you to reorder the menu items in the order you wish while explaining the nuances of the WordPress menu system.

乍看之下,WordPress中的管理系统运行良好。 内置菜单功能可解决许多问题,例如添加和删除菜单项,但您可能想了解有关WordPress如何在内部处理其菜单以利用更多控制权的更多信息。 下面的示例将说明如何实现一个插件,该插件使您可以在解释WordPress菜单系统的细微差别的同时,按希望的顺序对菜单项进行重新排序。

WordPress如何订购菜单项 (How WordPress orders Menu Items)

To best show how the position of a menu item can cause problems, let’s create a small plugin to demonstrate the way in which WordPress orders menu items when adding them.

为了最好地显示菜单项的位置如何导致问题,让我们创建一个小插件来演示WordPress添加菜单项时订购菜单项的方式。

Create a directory in the plugins directory, such as <root-installation>/wp-content/plugins/adminpagearranger. Then, create a file called init.php in the directory and use the WordPress plugin descriptor syntax to identify the plugin to the system.

plugins目录中创建一个目录,例如<root-installation>/wp-content/plugins/adminpagearranger 。 然后,在目录中创建一个名为init.php的文件,并使用WordPress插件描述符语法识别系统插件。

The WordPress documentation advises that adding admin pages should be done with the admin_menu action hook, so add this directly under the descriptor.

WordPress文档建议添加管理页面应使用admin_menu操作钩完成,因此请直接在描述符下添加。

The easiest way to add a menu item to the administration panel is with the add_menu_page() function which takes seven arguments:

将菜单项添加到管理面板的最简单方法是使用add_menu_page()函数,该函数带有七个参数:

  • text that is displayed in the title of the page

    页面标题中显示的文本
  • the text of the menu item which is used in displaying the menu item

    用于显示菜单项的菜单项的文本
  • the capability that you define to allow access to this menu item

    您定义的允许访问此菜单项的功能
  • a menu slug identifier which identifies this menu from any other in the system

    菜单项标识符,用于从系统中的任何其他菜单中标识此菜单
  • a function which renders the page in the browser

    在浏览器中呈现页面的功能
  • the path to an icon which is used to display with the menu, and

    用于与菜单一起显示的图标的路径,以及
  • the position that the new menu item should appear in relation to other menu items

    新菜单项应相对于其他菜单项出现的位置

Place the following code in init.php:

将以下代码放在init.php

<?php
/*
Plugin Name: Admin Page Arranger
Plugin URI: http://www.example.com/adminpagearranger
Description: A plugin to adminster admin pages
Version: 0.1
Author: Tim Smith
Author URI: http://www.example.com/
License: GPL2
*/

add_action("admin_menu", "addMenu");

function addMenu() {
    add_menu_page("My New Menu", "My New Menu", "edit_posts",
        "mynewmenu", "displayPage", null, 1);
}

The code will generate a new page link which sits at the top of the menu structure, just above the Dashboard:

该代码将生成一个新页面链接,该链接位于菜单结构的顶部,就在仪表板上方:

But, consider the following implementation of addMenu() instead:

但是,请考虑以下addMenu()实现:

<?php
function addMenu() {
    add_menu_page("My New Menu", "My New Menu", "edit_posts",
        "mynewmenu", "displayPage", null, 2);
}

Just by changing the position from 1 to 2 replaces the Dashboard entry with your new menu! Why? It’s all got to do with how WordPress stores its menu configuration.

只需将位置从1更改为2,即可用新菜单替换仪表板条目! 为什么? 这与WordPress如何存储其菜单配置有关。

WordPress uses a global array called $menu to store the menu configuration, and each key in the array represents the position in the menu. A higher position in the array indicates a higher position in the menu. However, WordPress populates this array on start up with default values. For example:

WordPress使用一个名为$menu的全局数组来存储菜单配置,并且数组中的每个键都代表菜单中的位置。 数组中较高的位置表示菜单中的较高位置。 但是,WordPress在启动时会使用默认值填充此数组。 例如:

Array
(
    [2] => Array
        (
            [0] => Dashboard
            [1] => read
            [2] => index.php
            [3] => 
            [4] => menu-top menu-top-first menu-icon-dashboard
            [5] => menu-dashboard
            [6] => div
        )

    [4] => Array
        (
            [0] => 
            [1] => read
            [2] => separator1
            [3] => 
            [4] => wp-menu-separator
        )

    [5] => Array
        (
            [0] => Posts
            [1] => edit_posts
            [2] => edit.php
            [3] => 
            [4] => open-if-no-js menu-top menu-icon-post
            [5] => menu-posts
            [6] => div
        )

    [10] => Array
        (
            [0] => Media
            [1] => upload_files
            [2] => upload.php
            [3] => 
            [4] => menu-top menu-icon-media
            [5] => menu-media
            [6] => div
        )
...
)

Each entry in the array is in fact another array providing the details of each menu item. So when the call to add a menu item at position 2 is executed, it actually replaces whatever may have been at position 2 prior. In this case, this is the dashboard’s information.

实际上,数组中的每个条目都是提供每个菜单项详细信息的另一个数组。 因此,在执行将菜单项添加到位置2的调用时,它实际上替换了之前在位置2可能发生的任何操作。 在这种情况下,这就是仪表板的信息。

When you’re adding a new menu item, be mindful of the position you specify. Note also that the arguments supplied to the add_menu_page() function have now been used to populate the global array.

添加新菜单项时,请注意您指定的位置。 还要注意,提供给add_menu_page()函数的参数现在已用于填充全局数组。

指定自定义菜单顺序 (Specifying a Custom Menu Order)

Now that you know how WordPress stores its menu configuration, you can use this to control where menu items appear in the $menu array and thus change the order in which the menus appear. WordPress offers two filters which can be used to change the menu: menu_order and custom_menu_order.

现在您已经知道WordPress如何存储其菜单配置,您可以使用它来控制$menu数组中菜单项的显示位置,从而更改菜单的显示顺序。 WordPress提供了两个可用于更改菜单的过滤器: menu_ordercustom_menu_order

custom_menu_order requires a Boolean value to be returned which indicates whether a custom menu should be used. In effect, the returned value from custom_menu_order dictates whether the menu_order filter is applied.

custom_menu_order需要返回一个布尔值,该值指示是否应使用自定义菜单。 实际上, custom_menu_order返回的值指示是否应用menu_order过滤器。

The return value of the custom_menu_order filter should return an array detailing the slugs of the menus you want to appear in their order. You can use the following table to select the slugs which relate to the standard menu items.

custom_menu_order过滤器的返回值应返回一个数组,其中详细列出了custom_menu_order顺序显示的菜单项。 您可以使用下表选择与标准菜单项相关的子弹。

<?php
add_filter("custom_menu_order", "allowMenuStructure");
add_filter("menu_order", "loadMenuStructure");

function allowMenuStructure() {
    return true;
}

function loadMenuStructure() {
    return array("index.php", "tools.php");
}

You don’t have to specify all of the slugs to be displayed when returning the array from custom_menu_order; WordPress will automatically populate the rest of the menu with the remaining menu items in the order they would normally be placed.

custom_menu_order返回数组时, custom_menu_order指定要显示的所有子段; WordPress将自动按照其余菜单项的正常放置顺序填充其余菜单项。

创建一个自定义菜单管理器 (Creating a Custom Menu Manager)

We can leverage the custom_menu_order filter to populate the menu in the desired order by storing an array in WordPress to be returned when this filter is applied. You do this by way of update_option which either creates or updates a value which you can call later with get_option(). WordPress stores the data in the database table wp_options for later retrieval. If the option has not yet been sent, or is absent for whatever reason, you can create it based on the default menu structure.

我们可以利用custom_menu_order过滤器,通过在WordPress中存储一个数组来按所需顺序填充菜单,该数组将在应用此过滤器时返回。 您可以通过update_option来执行此操作,后者会创建或更新一个值,稍后您可以使用get_option()进行调用。 WordPress将数据存储在数据库表wp_options以供以后检索。 如果尚未发送该选项,或者由于某种原因而没有该选项,则可以基于默认菜单结构来创建它。

The first thing you should do is add your own menu item so that you can administer the menu order. The returned value from add_menu_page() is a “hook suffix” which you can append to a number of action hooks which are specific to the page. The one we are interested in here is load-page_hook where page_hook should be substituted with the hook suffix.

您应该做的第一件事是添加自己的菜单项,以便您可以管理菜单顺序。 从add_menu_page()返回的值是一个“钩子后缀”,您可以将其附加到特定于页面的多个动作钩子上。 我们在这里感兴趣的是load- page_hook ,其中应该用钩子后缀替换page_hook

This hook is an ideal place to process form submissions as it will only occur when this page is loaded.

该钩子是处理表单提交的理想位置,因为它仅在加载此页面时才会发生。

Change the addMenu() function we used earlier to test the menu functionality as follows:

更改我们之前用来测试菜单功能的addMenu()函数,如下所示:

<?php
function addMenu() {
    $page = add_menu_page("Admin Manager", "Admin Manager",
        "manage_options", "adminmanager", "displayAdminManager",
        null, null);
    add_action("load-" . $page, "handleMenu");
}

This short piece of code obliges us define two more functions – displayAdminManager() which is responsible for displaying the page and handleMenu() which we will use to process any changes we make to the menu order.

这段简短的代码使我们handleMenu()定义另外两个函数– displayAdminManager()用于显示页面)和handleMenu()将用于处理对菜单顺序所做的任何更改)。

Before you define these, however, it makes sense to define a function which loads a menu structure obtained from the wp_options table or sets up a default. This function will be used in a couple of places.

但是,在定义这些函数之前,先定义一个函数,该函数可以加载从wp_options表获得的菜单结构或设置默认值。 此功能将在几个地方使用。

<?php
function getMenuStructure() {
    $structure = get_option("menustructure");
    if (!$structure) {
        global $menu;
        $newMenu = array();
        foreach ($menu as $menuItem) {
            $newMenu[] = $menuItem[2];
        }
        return $newMenu;
    }
    else {
        return $structure;
    }
}

getMenuStructure() uses get_option() to attempt to pull a menu structure from the database. If it isn’t available, then it constructs an array to pass back. This function will be used to actually populate your new menu structure and also to list the menu items when displaying the plugin so you can move the items up and down the structure.

getMenuStructure()使用get_option()尝试从数据库中拉出菜单结构。 如果不可用,则构造一个数组以传递回去。 此功能将用于实际填充新菜单结构,并在显示插件时列出菜单项,以便您可以在结构上上下移动菜单项。

You may find that some plugin developers place their own menu items wherever they want. This can sometimes be inconvenient as you will find that the normal menu items will be separated from where they should be. Plugin developers are dissuaded from doing this in general, but you’ll find occasionally someone feels their plugin is more important than the others and so they add it to the top of the menu system. If you want to get around this and make sure that all other additional menu items are placed below everything else, you can change the function to:

您可能会发现一些插件开发人员将他们自己的菜单项放置在所需的位置。 有时这可能会带来不便,因为您会发现普通菜单项将与应有的位置分开。 插件开发人员通常不愿这样做,但是您会发现偶尔有人会觉得他们的插件比其他插件更重要,因此他们将其添加到菜单系统的顶部。 如果要解决此问题并确保所有其他菜单项都位于其他所有菜单项下方,则可以将功能更改为:

<?php
function getMenuStructure() {
    $structure = get_option("menustructure");
    if (!$structure) {
        return array("index.php", "separator1", "edit.php",
            "upload.php", "link-manager.php",
            "edit.php?post_type=page",
            "edit-comments.php", "separator2", "themes.php",
            "plugins.php", "users.php", "tools.php",
            "options-general.php", "separator-last");
    }
    else {
        return $structure;
    }
}

This enforces that the default WordPress menu structure is implemented and any other items will be displayed after it.

这将强制实施默认的WordPress菜单结构,并在其后显示其他任何项目。

In the hard-coded structure, noticed I also used separator entries. The separators should be identified uniquely with the word “separator” followed by an integer, a the last one should be identified as “separator-last”.

在硬编码结构中,注意到我还使用了分隔符条目。 分隔符应唯一地标识为“ separator”,后跟一个整数,最后一个应标识为“ separator-last”。

So now you have a generic function for obtaining a menu structure and you can look at defining the function to display the menu manager so that the menu can be manipulated. You’ll need to include links so that when clicked, they reload the page whereupon the load-page_hook action is run.

因此,现在您具有用于获取菜单结构的通用功能,并且可以查看定义该功能以显示菜单管理器,以便可以操作菜单。 您需要包括链接,以便在单击链接时可以重新加载页面,然后运行load- page_hook操作。

<?php
function displayAdminManager() {
    $menu = getMenuStructure();
    foreach($menu as $key => $menuitem) {
        $uplink = "admin.php?page=adminmanager&menuitem=" . $key . "&direction=up";
        $downlink = "admin.php?page=adminmanager&menuitem=" . $key . "&direction=down";
        echo $menuitem . ' - <a href="' . $uplink . '">Up</a> <a href="' . $downlink . '">Down</a><br>';
    }
}

Note that we call the page itself; the URL for this page is /admin.php?page=adminmanager. The adminmanager identifier is the slug that was set when you added the page via add_menu_page() which was the fourth argument. There are also a couple of arguments detailing the direction the menu item should be moved (i.e. up or down) and which menu item will be affected.

请注意,我们称为页面本身。 该页面的URL是/admin.php?page=adminmanageradminmanager标识符是您通过add_menu_page()添加页面add_menu_page()第四个参数)时设置的信息。 还有两个参数详细说明了菜单项的移动方向(即向上或向下)以及哪个菜单项将受到影响。

So, now you have a means by which we can pass arguments to process via load-page_hook which was defined as handleMenu(). The key to this is that we swap the menu items over depending on the direction that was specified and when this is done, you use update_option() to store your new menu structure. Then the viewer is redirected back to “this” page. This ensures the new menu is loaded and implemented.

因此,现在您有了一种方法,我们可以通过load- page_hook handleMenu()定义为handleMenu()将参数传递给处理。 这样做的关键是我们根据指定的方向交换菜单项,完成此操作后,您可以使用update_option()存储新的菜单结构。 然后将查看器重定向回“此”页面。 这样可以确保新菜单已加载并实现。

It is also a good idea to ensure that menu items cannot be moved off the structure by testing whether the menu item to be manipulated is the first or last in the array.

通过测试要操作的菜单项是数组中的第一个还是最后一个,以确保不能将菜单项移出结构也是一个好主意。

<?php
function handleMenu() {

    if (isset($_GET["menuitem"]) && isset($_GET["direction"])) {
        $structure = get_option("menustructure");
        $numberItems = count($structure);
        $lastIndex = $numberItems - 1;

        if (!$structure) {
            $menu = getMenuStructure();
        }
        else {
            $menu = $structure;
        }

        // if the menu item is to be moved UP the menu
        if ($_GET["direction"] == "down" && $_GET["menuitem"] != $lastIndex) {
            // move the menu up
            $currentIndex = $_GET["menuitem"];
            $nextIndex = $currentIndex + 1;

            $currentMenuItem = $menu[$currentIndex];
            $nextMenuItem = $menu[$nextIndex];

            $menu[$currentIndex] = $nextMenuItem;
            $menu[$nextIndex] = $currentMenuItem;

            update_option("menustructure", $menu);
        }
        //if the menu item is to be moved DOWN the menu
        elseif ($_GET["direction"] == "up" && $_GET["menuitem"] != 0)
        {
            //move the menu down
            $currentIndex = $_GET["menuitem"];
            $previousIndex = $currentIndex - 1;

            $currentMenuItem = $menu[$currentIndex];
            $previousMenuItem = $menu[$previousIndex];

            $menu[$currentIndex] = $previousMenuItem;
            $menu[$previousIndex] = $currentMenuItem;

            update_option("menustructure", $menu);
        }

        wp_redirect("admin.php?page=adminmanager");
    }
}

Redirection is necessary because of the order in which the actions take place. The load-page_hook action occurs after the custom_menu_order filter, so updating the “menustructure” option takes place but you won’t see the effect since the custom menu order has already been loaded. A redirect will ensure the new menu structure is implemented correctly by essentially “refreshing” the page and the WordPress life cycle.

由于操作发生的顺序,重定向是必要的。 load- page_hook操作在custom_menu_order过滤器之后发生,因此将更新“ menustructure”选项,但由于已加载自定义菜单顺序,因此您不会看到效果。 重定向将通过实质上“刷新”页面和WordPress生命周期来确保正确实现新菜单结构。

摘要 (Summary)

This tutorial taught you how the internal admin menus are structured in WordPress. You built a simple plugin to implement a system whereby you can change the order of the menu items. We used WordPress’s internal options to store and retrieve this data and a custom filter to ensure our custom menu order is implemented.

本教程教您如何在WordPress中构造内部管理菜单。 您构建了一个简单的插件来实现一个系统,您可以在其中更改菜单项的顺序。 我们使用WordPress的内部选项来存储和检索此数据,并使用自定义过滤器来确保实现我们的自定义菜单顺序。

James Threw / Shutterstock

詹姆斯·特鲁 / Shutterstock

翻译自: https://www.sitepoint.com/admin-menus-in-wordpress/

wordpress 菜单

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值