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
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityMore 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.
This should help you out buddy - http://wpveda.com/add-custom-classes-wpnavmenu-condition/
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.
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.