einicher.net

The code must do the talking

WordPress: Get second Menu Level only

25. September 2015

This function returns the second nav menu level of a wordpress custom menu according to the current active page.

<?php
	function wp_nav_submenu($menu_name, $post_id, $direct_output = true)
	{
		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);

			// first we get our current main menu entry id
			foreach ($menu_items as $item) {
				if ($item->object_id == $post_id) {
					if ($item->menu_item_parent) {
						$current_menu_id = $item->menu_item_parent;
					} else {
						$current_menu_id = $item->ID;
					}
					break;
				}
			}

			if (!empty($current_menu_id)) {

				// now we get every item that is our main menu entries decended
				$subs = array();
				foreach ($menu_items as $item) {
					if ($item->menu_item_parent == $current_menu_id) {
						$subs[] = $item;
					}
				}

				ob_start();
				// finaly we list our submenu entries
?>
			<ul class="sub-menu clearfix">
<?
				foreach ($subs as $sub) {
					$title = empty($sub->post_title) ? get_the_title($sub->object_id) : $sub->post_title;
?>
				<li<?=$sub->object_id == $post_id ? ' class="active"' : ''?>><a href="<?=get_permalink($sub->object_id)?>"><?=$title?></a></li>
<?
				}
?>
			</ul>
<?
				$output = ob_get_clean();
				if ($direct_output) {
					echo $output;
				} else {
					return $output;
				}
			}
		}
	}

Leave a Reply

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