1

okay so I'm using the following code to get my links...

<?php wp_nav_menu( array('theme_location' => 'primary', 'container' => '', 'menu_class' => 'mainnav') ); ?>

This is my CSS for the nav...

.mainnav a {
    font-family: gooddog_plainregular, Arial, sans-serif;
    font-size: 30px;
    color: #ffea00;
    text-decoration:none;
}

.mainnav li:after {
content: url('images/nav-divider.png');
}

.mainnav li.last:after {
content: none;
}

.mainnav li {
    list-style: none;
    display: inline;
    font-size: 30px;
    margin-bottom: 10px;
}

.mainnav li.last {
    list-style: none;
    display: inline;
    font-size: 30px;
    margin-bottom: 10px;
}

The problem I'm having is that the li.last doesn't work, how do I add the class to it?

Thanks :)

| improve this question | | | | |
  • Are you trying to use the last-child pseudo-selector? – s_ha_dum Apr 6 '14 at 18:04
  • 1
    Do you plan to post the solution? – s_ha_dum Apr 6 '14 at 18:16
  • 1
    From the sounds of it, he wanted to add a class but ended up going with li:last-child as you suggested. – Howdy_McGee Apr 9 '14 at 18:15
4

Here's a function I use to add a first / last class to wp_nav_menu() items:

function add_first_and_last($items) {
    $items[1]->classes[] = 'first';
    $items[count($items)]->classes[] = 'last';
    return $items;
}
add_filter('wp_nav_menu_objects', 'add_first_and_last');

Developer Resources - wp_nav_menu_objects Hook

| improve this answer | | | | |
3

Use the last-child pseudoclass in the CSS:

.mainnav li:last-child
  {
    /* your code */
  }
| improve this answer | | | | |
1

The function mentioned by Howdee_McGee was great, but only seemed to work for menus without sub menu items. For a menu with sub menu items, try:

function add_first_and_last_top_level($items) {
$topitems = [];
foreach($items as $menu_item){
    if($menu_item->menu_item_parent==0){
        $topitems[] = $menu_item->menu_order;
    }        
}
$itemcount = end($topitems);
$items[1]->classes[] = 'menu-item-first';
$items[$itemcount]->classes[] = 'menu-item-last';
return $items;
}

add_filter('wp_nav_menu_objects', 'add_first_and_last_top_level');
| improve this answer | | | | |

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.