0

I need to alter my menu URLs and add "/" to the beginning on every page except homepage. It works well using this piece of code:

function change_menu($items){

    if(!is_front_page()){
        foreach($items as $item){
            $item->url = "/" .  $item->url;
        }
    }

    return $items;
}

add_filter('wp_nav_menu_objects', 'change_menu');

However, I also need to limit it to only first-level items (all the items in the sub-menu should remain the same). I know there is 'depth' argument available, but I have no clue how to use it.

UPDATE: My intention was to filter anchor links from classic ones. I have a microsite, which uses menu items as an anchor links. One of them has a submenu with links to custom subpages. Adding a slash at the beginning of all menu links on every subpage pointed the anchors to homepage (which works well), however it messed up the classic links.

I managed to write a workaround:

// if the URL is an anchor, add a slash   
if (strpos($item->url, '#!/') !== false) {
    $item->url = "/" .  $item->url;
}

However I would like to hear some ideas, if it can be done in a more elegant way.

0

depth argument, available in functions attached to wp_nav_menu_objects hook, refers to the max depth of rendered menu (how many menu levels will be visible on site).

To change only first-level elements, you can check in the loop if the menu item has a parent.

function change_menu($items) {

    if( !is_front_page() ) {
        foreach($items as $item) {
            if ( $item->menu_item_parent != 0 )
                continue;
            $item->url = "/" .  $item->url;
        }
    }
    return $items;
}

add_filter('wp_nav_menu_objects', 'change_menu');

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.