如何在插件菜单中使用WordPress默认的菜单图标

作为WordPress主题或插件开发者,你可能知道通过 add_menu_page() 函数来给你的主题或插件添加一个顶级菜单,并且通过 $icon_url 参数来定义一个菜单图标。但是如果你想直接调用WordPress默认的菜单图标的话,请继续往下看。

每个WordPress菜单图标都对应一个CSS类,你可以通过它来和你的自定义菜单进行关联。以下是 WP 3.5.2 所用图标(以后的图标版本可能会不一样)

using-default-admin-menu-icons-wpdaxue_com

WordPress会自动分配一个图标和CSS类给没有自定义图标的菜单,add_menu_page() 函数没有办法自定义菜单的 CSS 类,唯一的办法就是直接修改用户存储顶级菜单的全局 $menu 数组。以下是一个专门解决这个问题的函数:

/**
 * 将菜单的图标设置为任何一个WordPress默认菜单图标
 *
 * @param 字符串 $menu_slug 是传递给 add_menu_page() 函数的菜单别名或链接
 * @param 字符串 $icon_class_name 是图标的 CSS 类,例如 "menu-icon-settings".
 * @return bool True if the menu was found and modified successfully, false otherwise.
 */
function set_menu_icon_class($menu_slug, $icon_class_name) {
    global $menu;
 
    $slug_index = 2;
    $css_class_index = 4;
    $icon_url_index = 6;
 
    foreach ($menu as $position => $item) {
        if ( $item[$slug_index] == $menu_slug ) {
            $item[$icon_url_index] = '';
            $item[$css_class_index] .= ' ' . $icon_class_name;
 
            $menu[$position] = $item;
            return true;
        }
    }
 
    return false;
}

该函数的使用范例:将 menu-icon-site 这个图标添加到别名为 example-menu 的菜单中

function create_example_menu() {
    $menu_slug = 'example-menu';
    add_menu_page(
        'Example Menu',
        'Example Menu',
        'read',
        $menu_slug,
        '__return_null' //Will result in an empty page.
    );
 
    set_menu_icon_class($menu_slug, 'menu-icon-site');
});
add_action('admin_menu', 'create_example_menu');

参考资料:http://w-shadow.com/blog/2012/07/10/using-default-admin-menu-icons/

来源:

https://www.wpdaxue.com/using-default-admin-menu-icons.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32260.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?