WordPress.org

Ready to get started?Download WordPress

Forums

wp_nav_menu add a parent class (7 posts)

  1. fraticiudan
    Member
    Posted 3 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
    Member
    Posted 3 years ago #

    Super-easy with jQuery:

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

    $("ul.sub-menu").parents().addClass('parent');
    }

    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
    Member
    Posted 3 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.

    Cheers.

  4. begis
    Member
    Posted 3 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
    Member
    Posted 3 years ago #

    Thank you, fraticiudan!

    Your solution saved me a lot of work.

  6. cornhustlah
    Member
    Posted 3 years ago #

  7. duzymaju
    Member
    Posted 2 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

Tags