1

I'm trying to make a menu with wp_nav_menu(). I'm trying to add multiple classes but I don't have experience with this. I think I have to overwrite a class but ...

<div class="top-menu">
<ul class="nav_menu">        
    <li class="nav_menu-item"><a href="javascript:void(0)" class="nav-p">PRODUCTS</a>
    <!-- ... -->
    </li>
    <li class="nav_menu-item"><a href="javascript:void(0)" class="nav-n">NEW</a>
        <ul class="nav_submenu">
        <!-- ... -->
        </ul>
    </li>
    <li class="nav_menu-item">
    <!-- ... -->
    </li>
    <li class="nav_menu-item">
    <!-- ... -->
    </li>
</ul>

Could you help me with the code?

1

I don't know what your conditions are for each class by the hook you're looking for is nav_menu_css_class. You can use it to append classes or remove classes from each list-item <li> in the menu.

/**
 * Modify list item classes of wp_nav_menu
 * - https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_css_class
 * - https://developer.wordpress.org/reference/hooks/nav_menu_css_class/
 *
 * @param Array $classes || List of list-item classes
 * @param WP_Nav_Item Object $item || The Nav Menu Object, NOT the WP_Post object
 *
 * @return Array $classes
 */
function my_special_nav_class( $classes, $item ) {

    $menu_to_test_against = 'MENU NAME HERE';

    // Ensure we only apply this filter on the menu of our choice
    if( ! has_term( $menu_to_test_against, 'nav_menu', $item ) ) {
        return $classes;
    }

    $classes[] = 'nav-p';
    $classes[] = 'nav-n';

    return $classes;
}
add_filter( 'nav_menu_css_class', 'my_special_nav_class', 10, 2 );

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.