add_menu_classes() WordPress Function

The add_menu_classes() function allows you to add custom classes to menu items in WordPress. This can be useful for adding custom styles to your menus, or for targeting specific menu items with JavaScript.

add_menu_classes( array $menu ) #

Adds CSS classes for top-level administration menu items.


Description

The list of added classes includes .menu-top-first and .menu-top-last.


Top ↑

Parameters

$menu

(array)(Required)The array of administration menu items.


Top ↑

Return

(array) The array of administration menu items with the CSS classes added.


Top ↑

Source

File: wp-admin/includes/menu.php

function add_menu_classes( $menu ) {
	$first_item  = false;
	$last_order  = false;
	$items_count = count( $menu );
	$i           = 0;

	foreach ( $menu as $order => $top ) {
		$i++;

		if ( 0 == $order ) { // Dashboard is always shown/single.
			$menu[0][4] = add_cssclass( 'menu-top-first', $top[4] );
			$last_order = 0;
			continue;
		}

		if ( 0 === strpos( $top[2], 'separator' ) && false !== $last_order ) { // If separator.
			$first_item             = true;
			$classes                = $menu[ $last_order ][4];
			$menu[ $last_order ][4] = add_cssclass( 'menu-top-last', $classes );
			continue;
		}

		if ( $first_item ) {
			$classes           = $menu[ $order ][4];
			$menu[ $order ][4] = add_cssclass( 'menu-top-first', $classes );
			$first_item        = false;
		}

		if ( $i == $items_count ) { // Last item.
			$classes           = $menu[ $order ][4];
			$menu[ $order ][4] = add_cssclass( 'menu-top-last', $classes );
		}

		$last_order = $order;
	}

	/**
	 * Filters administration menu array with classes added for top-level items.
	 *
	 * @since 2.7.0
	 *
	 * @param array $menu Associative array of administration menu items.
	 */
	return apply_filters( 'add_menu_classes', $menu );
}


Top ↑

Changelog

Changelog
VersionDescription
2.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.