Because I want to add <span class="dashicons [class]"></span>
inside each link of my menu I needed to create a custom made nav menu. I did this by the code below which works great, but there is 1 problem.
I use custom links for showing post type archives in the menu. And I make a comparison between the page's post ID and the object ID of an item to check if the item is the current page. But with custom links, the object ID does not exists, so I cannot make the comparison.
$location = 'header-navigation';
if( ( $locations = get_nav_menu_locations() ) && isset( $locations[$location] ) ) {
global $post;
$post_id = $post->ID;
$menu = wp_get_nav_menu_object( $locations[$location] );
$menu_items = wp_get_nav_menu_items( $menu->term_id );
$menu_list = '<nav class="site-navigation">';
$menu_list .= '<ul id="menu-' . $location . '" class="grid-container">';
foreach( ( array ) $menu_items as $key => $menu_item ) {
$id = $menu_item->ID;
$title = $menu_item->title;
$classes = $menu_item->classes;
$object_id = get_post_meta( $id, '_menu_item_object_id', true );
$current = ( $object_id == $post_id ) ? 'current-menu-item' : '';
$menu_list .= '<li id="menu-item-' . $id . '" class="' . $current . '"><a href="' . $menu_item->url . '"><span class="dashicons ' . $classes[0] . '"></span>' . $title . '</a></li>';
}
$menu_list .= '</ul>';
$menu_list .= '</nav>';
echo $menu_list;
}