Custom shortcode to list menu items associated with page

Mods and Stuff for WordPress
Post Reply
User avatar
syntax
Site Admin
Posts: 54
Joined: Tue Jan 06, 2009 9:25 pm

Custom shortcode to list menu items associated with page

Post by syntax » Wed Dec 17, 2014 5:40 pm

Code: Select all

//list menus shortcode
function syn_menu_items($atts, $content=NULL) {
	ob_start();
	extract( shortcode_atts( array( 'menu' => '' ), $atts ) );
	$string = $atts['menu'];
	
	$menu = wp_get_nav_menu_items( $string );
	if (!empty($menu)) {
		$post_ID = get_the_ID();
		foreach ($menu as $item) {
			if ($post_ID == $item->object_id) {
				syn_menu_items_list_from_parent($menu, $item->ID);
				break;
			}
		}
	}
	
	return ob_get_clean();  
}
function syn_menu_items_list_from_parent($menu_items, $from_parent) {
	$items_to_list = array();
	foreach ($menu_items as $item) {
		if ($item->menu_item_parent == $from_parent) {
			$i = count($items_to_list);
			$items_to_list[$i]['url'] = $item->url;
			$items_to_list[$i]['title'] = $item->title;
			$items_to_list[$i]['ID'] = $item->ID;
		}
	}
	if (!empty($items_to_list)) {
		echo "<ul class='syn-menu-items'>";
		foreach ($items_to_list as $item) {
			echo "<li>";
			if ($item['url'] != '#') { echo "<a href='" . $item['url'] . "'>"; }
			echo $item['title'];
			if ($item['url'] != '#') { echo "</a>"; }
			echo "</li>";
			syn_menu_items_list_from_parent($menu_items, $item['ID']);
		}
		echo "</ul>";
	}
}
add_shortcode('syn_menu_items', 'syn_menu_items');
Usage: [syn_menu_items menu="Main Menu"]

Post Reply