<?php
/*
** -------------------------------------------
** Return next top level menu item
** -------------------------------------------
** usage: $next_menu_item = elbone_next_menu_item(get_the_ID(), 'primary');
*/

function elbone_next_menu_item($post_id, $menu_name) {

	if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {

		// Get the menu object
		$menu = wp_get_nav_menu_object($locations[$menu_name]);

		// Escape if no menu
		if (!isset($menu->term_id))
			return false;
			
		// Get all menu items
		$args = array(
			'order' => 'ASC',
			'orderby' => 'menu_order',
			'post_type' => 'nav_menu_item',
			'post_status' => 'publish',
			//'output' => OBJECT,
			'output_key' => 'menu_order',
			'nopaging' => true,
			'update_post_term_cache' => false 
		);
		$menu_items = wp_get_nav_menu_items($menu->term_id);

		// Escape if no menu items
		if (!isset($menu_items))
			return false;

		// Build array of menu item post IDs
		$post_ids = array();
		foreach ($menu_items as $key => $value) {
			$post_ids[] = get_post_meta($value->ID, '_menu_item_object_id', true);
		}

		// Get key of current post_id
		$current_post_key = array_search($post_id, $post_ids);
		$next_post_key = $current_post_key + 1;

		// if no item with that key return false
		if (!isset($post_ids[$next_post_key]))
			return false;

		// Got his far so lets return the post
		$next_post_ID = $post_ids[$next_post_key];
		return get_page($next_post_ID) ? get_page($next_post_ID) : get_post($next_post_ID);

	}
	
	return false;
}

?>