• In a previous forum post, Kuroi posted a solution for adding first and last classes to a menu, but I ran into an issue implementing it I wanted to post the solution for. Since that thread is closed, I’m posting it here.

    The issue came when I specified that an entry in the menu have a specific class via wp-admin. Here was my (cludgy) fix:

    function add_first_and_last($output) {
      $output = preg_replace('/class="(\w*\s)?menu-item/', 'class="$1first-menu-item menu-item', $output, 1);
      $pos=strripos($output, 'class="menu-item');
      $len=strlen('class="menu-item');
      $rep='class="last-menu-item menu-item';
      //double-check for a later entry with menu-item later in the
      //class list
      if(strripos($output, ' menu-item ')>$pos){
    	  $pos=strripos($output, ' menu-item ');
    	  $len=strlen(' menu-item ');
    	  $rep=' last-menu-item menu-item ';
      }
      $output = substr_replace($output, $rep, $pos, $len);
      return $output;
    }
    add_filter('wp_nav_menu', 'add_first_and_last');

    If there is a better way, please reply and enlighten. Thanks.

Viewing 1 replies (of 1 total)
  • You can use CSS alone if you don’t mind the styling only aplying to the more modern browsers.

    ul#somemenu > li:first-child { }
    ul#somemenu > li:last-child { }

    Or you could use some jQuery to add additional classes..

    <script type="text/javascript">
    /* <![CDATA[ */
    jQuery(document).ready( function($) {
    	$('#somemenu > li:first-child').addClass('first-item');
    	$('#somemenu > li:last-child').addClass('last-item');
    } );
    /* ]]> */
    </script>

    jQuery won’t have the same browser limitations, but obviously will mean loading jQuery frontside (if plugins or the theme are already doing this it should have minimal impact on load times).

    Now you have 3 different approaches.. 😉

Viewing 1 replies (of 1 total)
  • The topic ‘First and Last classes on menus – solution’ is closed to new replies.