How To Move The Custom Menu Item Classes To The Anchor Element

A common need of WordPress developers is adding custom classes to menu items. Using a custom class allows menu items to be styled differently, perhaps more like a button which is becoming more and more common.

An example of a website I’ve built with a nav item item styled like a button

WordPress does offer custom classes for menu items. If you can’t see a field for adding a CSS Class then you may need to enable it in your screen settings. Adding your classes to this field will add those classes to the menu item’s <li> element.

However sometimes these classes should be applied to the anchor tag rather than the list element. This is particuarly important when using a front-end framework such as Bootstrap, or icon fonts such as Font Awesome.

A lot of the solutions out there suggest using a custom walker. While custom walkers are extremely powerful, they’re usually overkill for this sort of thing. We only want to add and remove some classes and WordPress already provides the filters we need to do this. I’ve also run into issues with plugins that don’t work as they expect the menus to be running the same filters that core does, which is something often overlooked when building a custom walker.

Simply paste the below snippet into your theme’s functions.php file and it will add your custom menu item classes to the anchor tag instead of the list item element.

Did you find this post useful?