How To Use The Default Admin Menu Icons In Your Plugin

As you probably know, you can use the add_menu_page() function to create a top level admin menu for your WordPress plugin or theme. This function allows you to specify a menu icon by passing an image URL as the $icon_url argument. But what if you want to use one of the default admin icons – like, say, the “Tools” menu icon – instead of a custom image? Read on.

Each of the default icons has a corresponding CSS class that you can use to assign that icon to your custom menu.  Here’s a complete list of admin menu icons available in the default admin theme of WordPress 3.4.1 (other themes or versions may have different icons):

To use one of these icons in your plugin, you’ll need to remove the default menu icon that WordPress automatically assigns to menus created without an icon URL and add the appropriate CSS class instead. The add_menu_page() function doesn’t provide a way to specify the CSS class, so the only way to do this is to directly modify the global $menu array that WP uses to store top level menus. To make this task simpler, I’ve written a quick utility function that does it for you:

/**
 * Set a menu's icon to one of the default Dashboard menu icons.
 *
 * @param string $menu_slug The menu slug or URL that you passed to add_menu_page().
 * @param string $icon_class_name Icon CSS class, e.g. "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;
}

Usage example:

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');

Here’s what the menu created by the above code will look like:

And that’s all there is to it. I hope you found this tip useful 🙂

Related posts :

3 Responses to “How To Use The Default Admin Menu Icons In Your Plugin”

  1. […] => 'my-menu-class' ) ); To learn more about the menus visit the codex page, wp_nav_menu.WordPress offers you a lot of styling options for your menu right out of the box. By default, the me…>.menu-item – This class is added to every menu item. .menu-item-object-{object} – This class is […]

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

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

Leave a Reply