• I’m only opening this thread because the thread from a year ago on the topic found here is closed.

    Why is it that this feature isn’t available right out of the box? There are already 5 or 6 different classes tagged onto any given menu item, why not add first and last classes to the LIs in the menus(and for the sake of it, middle)? As the last person in that thread mentioned, this should be default behavior.

    The question I’m wondering is if there is a better way to go about this in the year since this question was posed? I’ve seen solutions elsewhere talking about adding classes to the menus manually, but that is just impractical. I’m building a site for a client that has the flexibility for them to add and change the menus as they see fit, so having first and last classes added there is impractical as I can’t assume the menus won’t be rearranged at some point unbeknownst to me.

    If that is still the best solution, how and where do I go about implementing it? It isn’t spelled out and I’m not much of a WordPress Dev to know where it should go.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Because these pseudo classes are not supported by anything other than the most current browsers?

    Thread Starter slideaway

    (@modsuperstar)

    I’m not asking here about pseudo classes here. Pseudo classes are precisely why this is required, because they can’t be relied on in 100% of browser situations.

    The code in that thread still works:

    /*
     add first and last classes to nav menus
     */
    
    function add_first_and_last($output) {
      $output = preg_replace('/class="menu-item/', 'class="first-menu-item menu-item', $output, 1);
      $output = substr_replace($output, 'class="last-menu-item menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item'));
      return $output;
    }
    add_filter('wp_nav_menu', 'add_first_and_last');

    Add this code to your functions.php file in your custom theme

    If you don’t have a functions.php make a new file and add <?php to the top of it and paste that code. The end result will be a file that looks like this in the root directory of your custom theme / child theme:

    <?php
    
     /*
     add first and last classes to nav menus
     */
    
    function add_first_and_last($output) {
      $output = preg_replace('/class="menu-item/', 'class="first-menu-item menu-item', $output, 1);
      $output = substr_replace($output, 'class="last-menu-item menu-item', strripos($output, 'class="menu-item'), strlen('class="menu-item'));
      return $output;
    }
    add_filter('wp_nav_menu', 'add_first_and_last');
    Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    You could always use jQuery.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Adding First and Last classes to menu items’ is closed to new replies.