Posted by & filed under Code.

I will be soon do a post on how to create your own custom menu. But what I have created is a function that I made whilst working out a way to add images instead of text to a menu item or adding images to an menu item.

There is a way to add a class to a specific menu item and that is if you click “Screen Options” on your Menu Page you can see “CSS Classes” this will allow you to add a class to a menu item. But if you are wanting to do this dynamically then it is hard due to WP not having a function to do this as they built it into the update of menu items. However, I have extracted the code that does this so that I could then easily add classes to a menu item in my theme if I wanted to. So here’s the code.

function add_menu_class($menu_item_db_id, $class) {
	$class = array_map( 'sanitize_html_class', explode( ' ', $class ) );
	update_post_meta( $menu_item_db_id, '_menu_item_classes', $class );

All you need is the menu item ID and the class you want.

Leave a Reply

  • (will not be published)