• Hello, i am searching for a working way to add a parent class to all menu items that have children, so i can format them different. If anyone has a link or description that allows me (being a beginner in php and themeediting) to succeed, i would be grateful.

    Thank you
    Sofian

Viewing 4 replies - 1 through 4 (of 4 total)
  • To target all the topmost menu items, I think you can use direct children selector ( or whatever it’s called ).

    Like this

    .nav-menu > ul > li > a { color: red; }

    To target only top menu items that have sub items, you have to put in custom class name.
    Appearance > Menus and pull down Screen Options tab

    Thread Starter Sofian777

    (@sofian777)

    Hello Paul,

    thanks for reply, the second one is indeed a solution that works. Yet i would like to avoid using the custom menu and keep it automated, so the search continues for a solution to make WP itself add a class to all menu items that have children, as some themes are doing it (graphene or the elegantthemes.com themes).

    Actually this should have been solved multiple times and i found some posts and descriptions in the net, but i couldnt find a clear outcome there and my programming knowledge keeps me in need of a step-by-step explanation (i can add a function but i cannot program it by myself).

    Any further ideas?

    Hi Sofian777, this should do it

    How to add a parent class for menu item
    https://codex.www.ads-software.com/Function_Reference/wp_nav_menu#How_to_add_a_parent_class_for_menu_item

    Thread Starter Sofian777

    (@sofian777)

    Thanks for this, i tried it out but i couldnt get it to work. I copied it into my functions.php like this, is there anything else i should have done? (creating the childtheme i have done right since the css also worked. the file is named correctly, so i cannot find where i made my newbie mistake:)

    <?php
    add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
    function add_menu_parent_class( $items ) {
    
        $parents = array();
        foreach ( $items as $item ) {
            if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {
                $parents[] = $item->menu_item_parent;
            }
        }
    
        foreach ( $items as $item ) {
            if ( in_array( $item->ID, $parents ) ) {
                $item->classes[] = 'menu-parent-item';
            }
        }
    
        return $items;
    }
    ?>
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Adding parent class to menu item’ is closed to new replies.