The add_menu_classes() WordPress PHP function adds CSS classes for top-level administration menu items. These classes include .menu-top-first and .menu-top-last, which are used to style the first and last menu items respectively.
Usage
You can use the add_menu_classes() function to add specific CSS classes to your administration menu items. Here’s an example:
$menu = array('Dashboard', 'Posts', 'Pages', 'Comments', 'Appearance'); $menu = add_menu_classes($menu); print_r($menu);
In this example, the add_menu_classes() function will return the $menu
array with added CSS classes for the first and last items.
Parameters
$menu (array)
: This is the required parameter. It is the array of administration menu items to which you wish to add classes.
More Information
See WordPress Developer Resources: add_menu_classes()
This function is part of the core WordPress code and is used internally to handle menu item styling. Always ensure to use it correctly to maintain the integrity of your admin menu.
Examples
Basic Usage
The code below adds CSS classes to an array of menu items.
$menu = array('Home', 'About', 'Services', 'Contact'); $menu = add_menu_classes($menu); print_r($menu);
This will add .menu-top-first
to ‘Home’ and .menu-top-last
to ‘Contact’.
Adding New Menu Items
This example shows how to add a new menu item and apply the add_menu_classes() function.
$menu = array('Home', 'About', 'Services', 'Contact'); array_push($menu, 'Blog'); $menu = add_menu_classes($menu); print_r($menu);
This will add .menu-top-last
to the new ‘Blog’ item.
Removing and Adding Menu Items
Here we’re removing a menu item, then adding a new one.
$menu = array('Home', 'About', 'Services', 'Contact'); unset($menu[1]); array_push($menu, 'Blog'); $menu = add_menu_classes($menu); print_r($menu);
This will remove ‘About’, add ‘Blog’, and add .menu-top-last
to ‘Blog’.
Reordering Menu Items
This example reorders the menu items before adding classes.
$menu = array('Home', 'About', 'Services', 'Contact'); $menu = array_reverse($menu); $menu = add_menu_classes($menu); print_r($menu);
This will reverse the menu order and add .menu-top-first
to ‘Contact’ and .menu-top-last
to ‘Home’.
Empty Menu Array
This shows what happens when you use an empty array.
$menu = array(); $menu = add_menu_classes($menu); print_r($menu);
As there are no menu items, no classes are added.