wp_nav_menu add a parent class (7 posts)

  1. fraticiudan
    Posted 5 years ago #

    Hi everyone,

    I'm playing with the [not so] new wp_nav_menu() and I like it. Only problem is I get no special class for menu items that have children items. Not sure I was clear enough, so here is an example:

    |-Item 1
    |-Item 2
      |-Subitem 2.1
      |-Subitem 2.2
    |-Item 3

    I just want some class for the "Item 2" because it has subitems. I looked at the Walker class, but I haven't been able to figure out a way to achieve this behaviour, Not sure it's posible.

    Is there a way to get this?

    Thank you.

  2. stevecoy
    Posted 5 years ago #

    Super-easy with jQuery:

    jQuery(document).ready(function($) {


    This will get you something like:

    <li class="page-item">Item 1
    <li class="page-item parent">Item 2
    <ul class="sub-menu">2nd level menu

    The reason this works is because WP automatically appends the sub-menu class to the 2nd level menus. Really, it should apply the "parent" class to the top-level menu items that have children automatically, too. Hmm, maybe a fix should be suggested to the WP developers?

  3. fraticiudan
    Posted 5 years ago #

    Thanks for the reply Steve, I found a solution eventually I just forgot to come back and share it.

    Here is my solution http://pastebin.com/DVEcci3e.

    It's a custom Walker that overrides the display_element function and adds the "parent" class to the current itrem if it has childens. I just added 2 lines ( 37-38 ).

    It can be done via javascript easly, but I don't like the solution as you get a flicker that moves the menu (in my case) as the code gets loaded/executed.


  4. begis
    Posted 5 years ago #

    Hi Dan,

    I would like to use your piece of code "Nfr_Menu_Walker" as a plugin. Could you point me how to do it? If I just put it into plugin without any apply_filters action, it seems not working.

    Of course, I use the wp_nav_menu('walker' => new Nfr_Menu_Walker()) construction...

    Thanx Begis

  5. derscheinwelt
    Posted 4 years ago #

    Thank you, fraticiudan!

    Your solution saved me a lot of work.

  6. cornhustlah
    Posted 4 years ago #

  7. duzymaju
    Posted 4 years ago #

    I have simple solution: MAJpage Menu Class Extender. Maybe it's not as fast and pure as above but it's great solution for people who can't programming - just install and turn on this plugin and use additional CSS classes in your menu

  8. tags: for first, last, parent, even and odd
  9. elements on every menu level.

Topic Closed

This topic has been closed to new replies.

About this Topic