How to change WordPress sub-menu class

Sometimes you need to customize the default WordPress menu system to add your own set of CSS classes. WordPress provides a couple of filters to do that.

I use these codes to add custom classes to list items and menu links in WordPress. Paste these in your functions.php file or your plugin file to make this work.

function ab_submenu_class($menu) { 
$menu = preg_replace('/ class="sub-menu"/','/ class="submenu" /',$menu); 
return $menu; 

If you want to add a class in the parent menu use the below functions

add_filter( 'wp_nav_menu_objects', 'ab_has_children_to_nav_items' );

function ab_has_children_to_nav_items( $items )
    $parents = wp_list_pluck( $items, 'menu_item_parent');
    foreach ( $items as $item )
        in_array( $item->ID, $parents ) && $item->classes[] = 'has-submenu parent-parent-menu-item';
    return $items;

That’s it. Refresh your browser and see the changes.

Leave a Reply

Your email address will not be published. Required fields are marked *