0

I try to hide some menu items (from an unique menu) dynamically in functions.php. I have some subdomains. I add CSS classes to menu items and then I hide them according to the current subdomain. Here is my code :

add_filter( 'wp_get_nav_menu_items', 'hide_menu_item', 10, 3 );
function hide_menu_item ( $items, $menu, $args ) {
    $sub = array_shift((explode(".",$_SERVER['HTTP_HOST'])));

    if(!is_admin()){
        foreach ( $items as $key => $item ) {
            if ( $item->classes[0] == 'subdomain1' && $sub != 'part1' || $item->classes[0] == 'main' && $sub != 'domain') {
                unset( $items[$key] );
            }
        }
    }
    return $items;
}

subdomain1 and main are classes, part1 is a subdomain and domain is the main domain. I.e. main is the class for the item Products, and subdomain1 is the class for the subitem Smartphone. Both of them are shown on domain.com, and Products is hidden on part1.domain.com. It works, but the problem is that Smartphone on subdomain part1 is ejected to the end of the menu while it was originally at the middle of the menu.

How can I do to 'keep' the position of the subitem, or the position of the hidden parent ?

  • When you had 'Smartphone' in the middle of the menu was that just alphabetical order (A-Z) or did you use 'order' numbers (on right of edit/quick edit view)? – Dub Scrib Aug 17 '15 at 10:41
  • @DubScrib I used the quick edit view to edit it so for sure it isn't in alphabetical order – Sovnfield Aug 17 '15 at 14:34
0

I found the answer in nav-menu.php, it wasn't too complicated. I just changed the foreach loop content like this :

if($item->classes[0] == 'subdomain1' && !empty( $item->menu_item_parent )){
    $item->menu_item_parent = '';
}elseif($item->classes[0] == 'main' && $sub != 'domain'){
    unset($items[$key]);
}

Hope it can help !

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.