1

I am using.

<?php wp_nav_menu($args); ?>

for get menu from wordpress.it returns the menus with <ul> and <li> structure. In that i need to set class name for every <li> tag uniquely.

thanks ravi

0

4 Answers 4

2

More easily, you can just enter a unique class name on the admin menu page /wp-admin/nav-menus.php. You may need to look in the top right corner of the page for "Screen Options" and then enable CSS Classes. Then edit any menu item and add the class.

1

This should help you out buddy - http://wpveda.com/add-custom-classes-wpnavmenu-condition/

0

Why?

You can add both ID and class to the containing UL tag, using arguments passed to wp_nav_menu(), which should give you more than enough specificity to target descendant LI tags.

What are you trying to do, specifically? I'm sure we can find a way to accomplish it.

0

The only way that I could think to do this would be to add a filter to wp_nav_menu_items. Here is the code that I got to work by adding an ID (just add it to your themes functions.php file and change it as needed. You should be able to do something similar for classes):

add_filter('wp_nav_menu_items', 'my_id_name_nav', 10, 2);
function my_id_name_nav($items,$args) {
  if( $args->theme_location == 'primary' ) {
    preg_match_all('/<li id="menu-item-([0-9]+)"([^>]+)>\s*<a href="([^"]+)">([^<]+)<\/a><\/li>/i', $items, $matches);
    $newItems = array();
    for($i=0; $i<count($matches[0]); $i++){
      $short = explode('/', $matches[3][$i]);
      $short = $short[count($short) - 2]; // if there is no trailing slash, subtract 1 instead of 2
      array_push($newItems, '<li id="menu-item-'. $short .'"'. $matches[2][$i] .'><a href="'. $matches[3][$i] .'">'. $matches[4][$i] .'</a></li>');
    }
    return implode('', $newItems);
  } else {
    return $items;
  }
}

It uses the last part of the url to create the page name for the class. So menu-item-2 for http://yoursite.com/page1/page2/ would become menu-item-page2.

The if( $args->theme_location == 'primary' ) is for targeting a specific menu. If you want to do this for all menus just remove the if else statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.