Using WordPress ‘add_cssclass()’ PHP function

The add_cssclass() WordPress PHP function adds a CSS class to a string.

Usage

The function is primarily used to add CSS classes to menu items in WordPress.

add_cssclass('new-class', 'existing-class');

This will return the string 'existing-class new-class'.

Parameters

  • $class_to_add (string) – The CSS class to add.
  • $classes (string) – The string to add the CSS class to.

More information

See WordPress Developer Resources: add_cssclass()

This function is defined in wp-admin/includes/menu.php, so it’s not immediately available on the frontend and its use there is probably discouraged.

Examples

Adding a class to a menu item

Here we are adding the ‘menu-top-first’ class to the first menu item.

$firstm = $lastm = false; 
$i = 0;
foreach ( $menu as $order => $top ) { 
  $i++; 
  if ( 0 == $order ) {
    // Adds 'menu-top-first' to the first menu item
    $menu[0][4] = add_cssclass( 'menu-top-first', $top[4] ); 
    $lastm = 0; 
    continue; 
  }
  ...
}

Adding a ‘menu-top-last’ class

This example adds the ‘menu-top-last’ class to the last menu item before a separator.

$firstm = true;
foreach ( $menu as $order => $top ) { 
  if ( 0 === strpos( $top[2], 'separator' ) && false !== $lastm ) {
    // Adds 'menu-top-last' to the last menu item before a separator
    $c = $menu[ $lastm ][4]; 
    $menu[ $lastm ][4] = add_cssclass( 'menu-top-last', $c );
    continue;
  }
  ...
}

Reassigning the ‘menu-top-first’ class

In the following snippet, the ‘menu-top-first’ class is reassigned to a new menu item.

$firstm = false;
foreach ( $menu as $order => $top ) { 
  if ( $first ) {
    // Reassigns 'menu-top-first' to a new menu item
    $c = $menu[ $order ][4]; 
    $menu[ $order ][4] = add_cssclass( 'menu-top-first', $c ); 
    $firstm = false; 
  }
  $lastm = $order; 
}

Adding multiple classes

You can use add_cssclass() to add multiple classes at once. Just separate the classes with a space.

$existing_classes = 'class1 class2';
$new_classes = 'class3 class4';
$classes = add_cssclass($new_classes, $existing_classes);

Adding a class conditionally

In this example, a CSS class is added to a variable only if a condition is met.

$classes = 'my-class';
if ($condition) {
  $classes = add_cssclass('additional-class', $classes);
}