Support » Plugins and Hacks » Hacks » Special Class for Menu Item

  • Resolved agiuliano8

    (@agiuliano8)


    Hi, I apologize in advance because I assume this has been asked and answered at least once before, however I can’t seem to find a thread that gets the job done for me.

    I’m using the built in functionality in Appearance -> Menus for a top level nav bar. I’d like to add a special class to one of the list items so I can style it differently to make it stand out. Is there something I can do in functions.php to accomplish this?

    As I’m writing this, I realized that I could probably use a psuedo element selector like ::last-child or nth-child for my purposes, but let’s assume there’s another reason I need a class on a specific list item in the nav bar, how would I go about that?

Viewing 7 replies - 1 through 7 (of 7 total)
  • Moderator t-p

    (@t-p)

    Are you using CSS3?

    You could use, for example the first item:

    ul#navmenuid:first-child {
         border-left: 1px;
    }

    Yea, I was playing around with pseudo selectors, and I could probably make it work for my purposes but I’m curious how I would go about adding a class to one of the nav elements.

    Moderator t-p

    (@t-p)

    try this:

    add_filter('nav_menu_css_class', 'add_active_class', 10, 2 );
    
    function add_active_class($classes, $item) {
      $class_names = array( 'current-menu-item', 'current-menu-ancestor', 'current-menu-parent', 'current_page_parent',  'current_page_ancestor' );
    
      if( $item->menu_item_parent == 0 && in_array( $class_names, $classes) ) {
        $classes[] = "active";
      }
    
      return $classes;
    }

    Thanks again for the response. Is that going to add a class called “active” to the menu item that corresponds to the current page? I’m really just looking to add it to a specific top level menu item, regardless of whether it’s the current page. Currently that menu item that I’m trying to target has an ID = “menu-item-104”, which I could use but I don’t know where it got that number, or under what circumstances, if any, it could change.

    I would be getting details like:
    ID = "menu-item-104"
    by using firebug.
    I share your dislike for this expedient technique which ties layout to specific content. The good news however is that these numbers are quite rhobust, it is tied to the creation of that element, so is unlikely to change.

    Cool, thanks for the help folks.

    Moderator t-p

    (@t-p)

    Glad you got it sorted 🙂

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Special Class for Menu Item’ is closed to new replies.