Home > Mobile >  How can I add a class to nav_menu items with a function?
How can I add a class to nav_menu items with a function?

Time:09-22

i'm using wordpress and i'm trying to add a class to the main nav menu-item li. I was able to figure out how to wrap the title with a div but how can i add a class to the entire li?

This is the filter function I was using to wrap the title:

add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);
function my_wp_nav_menu_objects( $items, $args ) {

    // loop
    foreach( $items as &$item ) {
        $item->title = "<div class='test'>".$item->title."</div>";
    }
    // return
    return $items;
}

but i want to add a class to the <li>.

CodePudding user response:

Actually, you can use replace in output. For instance you need to add my-class to nav-item

<?php
    $custom_menu = wp_nav_menu(array(
        'theme_location' => 'my_menu',
        'menu_id' => 'menu',
        'echo' => false
         )
    );
    $custom_menu = str_replace('nav-item', 'nav-item my-class', $consult_menu);
    echo $custom_menu;?>
  • Related