30 Nov -0001

Modifying wordpress menu code

I've recently needed to modify the wordpress menu code so that I could insert bootstrap classes directly into it.

Add the following to the functions file:

// custom menu example @ https://digwp.com/2011/11/html-formatting-custom-menus/
function clean_custom_menus() {
	$menu_name = 'nav-primary'; // specify custom menu slug
	if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
		$menu = wp_get_nav_menu_object($locations[$menu_name]);
		$menu_items = wp_get_nav_menu_items($menu->term_id);

		$menu_list = '<nav>' ."\n";
		$menu_list .= "\t\t\t\t". '<ul>' ."\n";
		foreach ((array) $menu_items as $key => $menu_item) {
			$title = $menu_item->title;
			$url = $menu_item->url;
			$menu_list .= "\t\t\t\t\t". '<li><a href="'. $url .'">'. $title .'</a></li>' ."\n";
		}
		$menu_list .= "\t\t\t\t". '</ul>' ."\n";
		$menu_list .= "\t\t\t". '</nav>' ."\n";
	} else {
		// $menu_list = '<!-- no list defined -->';
	}
	echo $menu_list;
}

Make sure to replace the menu slug. To do this make sure the menu is assigned to a location on Wordpress. The menu slug is infact the location using lowercase and dashes (for example: footer-menu).

To display the menu, insert the following into the theme:

<?php if (function_exists(clean_custom_menus())) clean_custom_menus(); ?>

More information on this function at this blog post