0

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;
}
  • I'd be surprised if this couldn't be done with all CSS, given that you are adding the span to all links. – s_ha_dum Nov 4 '15 at 17:21
  • @s_ha_dum I don't think so, because I need the classes from the menu items from database. – Robbert Nov 4 '15 at 18:53
0

I had to compare the $object_id with the current queried object id instead of the post id. https://www.robbertvermeulen.com/wp_get_nav_menu_items-current-menu-item/

$object_id  = get_post_meta( $id, '_menu_item_object_id', true );
$current    = ( $object_id == get_queried_object_id() ) ? 'current-menu-item' : '';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.