WordPress.org

Forums

[resolved] Special Class for Menu Item (8 posts)

  1. agiuliano8
    Member
    Posted 12 months ago #

    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?

  2. Tara
    Volunteer Moderator
    Posted 12 months ago #

    Are you using CSS3?

    You could use, for example the first item:

    ul#navmenuid:first-child {
         border-left: 1px;
    }
  3. agiuliano8
    Member
    Posted 12 months ago #

    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.

  4. Tara
    Volunteer Moderator
    Posted 12 months ago #

    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;
    }
  5. agiuliano8
    Member
    Posted 12 months ago #

    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.

  6. RossMitchell
    Member
    Posted 12 months ago #

    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.

  7. agiuliano8
    Member
    Posted 12 months ago #

    Cool, thanks for the help folks.

  8. Tara
    Volunteer Moderator
    Posted 12 months ago #

    Glad you got it sorted :)

Reply

You must log in to post.

About this Topic