Petr Pabouček
Freelance Web Developer

Prohlédněte si seznam mnou nabízených služeb, podívejte se, co o mě říkají mí klienti, či na jakých projektech jsem se podílel. V případě zájmu o spolupráci, či jakýchkoliv jiných dotazů, mě prosím kontaktujte.

Adding a CSS class to the all last menu items generated by wp_nav_menu

Today I’ve been working on one WordPress project where I needed to add CSS class  to the all last menu items generated by wp_nav_menu() function.  I’ve done little research on the Internet and found this article ‚Adding a CSS Class to the Last LI Generated by wp_nav_menu()‚. Works great so far, unfortunatelly it adds class just to the very last item of the list.

My task required to add CSS class to the all last menu items as follows:

<ul>
	<li>Item A
        <ul>
	         <li>Item a1</li>
	         <li>Item a2</li>
	         <li class="last">Item a3</li>
        </ul>
    </li>
	<li>Item B
        <ul>
	          <li>Item b1</li>
	          <li>Item b2</li>
	          <li class="last">Item b3</li>
        </ul>
    </li>
	<li class="last">Item C</li>
</ul>

Article mentioned above has been a great inspiration to me and after a while of playing with WordPress, I have come up with this code.

function add_last_item_class($menuHTML) {
  $last_items_ids  = array();

  // Get all custom menus
  $menus = wp_get_nav_menus();

  // For each menu find last items
  foreach ( $menus as $menu_maybe ) {

    // Get items of specific menu
    if ( $menu_items = wp_get_nav_menu_items($menu_maybe->term_id) ) {

      $items = array();
      foreach ( $menu_items as $menu_item ) {
        $items[$menu_item->menu_item_parent][] .= $menu_item->ID;
      }

      // Find IDs of last items
      foreach ( $items as $item ) {
        $last_items_ids[] .= end($item);
      }
   }
}

  foreach( $last_items_ids as $last_item_id ) {
    $items_add_class[] .= ' menu-item-'.$last_item_id;
    $replacement[]     .= ' menu-item-'.$last_item_id . ' last';
  }

  $menuHTML = str_replace($items_add_class, $replacement, $menuHTML);
  return $menuHTML;

}
add_filter('wp_nav_menu','add_last_item_class');

All you have to do, is copy and paste the code above into functions.php file located in your theme directory. It’s likely not the best solution, but worked for me. In case you are facing similar problem, this code should help you to safe some time of digging and coding.

Komentáře k článku

Your Comment