Adding different unique classes to WordPress wp_nav_menu?

I’m trying to put in different <img> tags in each <li> generated by wp_nav_menu().

Meaning I want wp_nav_menu to generate this:

Read More
<ul id="main-menu">
    <li id="menu-item-219" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-219">
        <a href="">
        <img id="icon-one" />
            Link One
        </a>
    </li>
    <li id="menu-item-220" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-220">
    <a href="">
        <img id="icon-two" />
        Link Two
        </a>
    </li>
</ul>

Instead of this (the original output):

<ul id="main-menu">
    <li id="menu-item-219" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-219">
        <a href="">
            Link One
        </a>
    </li>
    <li id="menu-item-220" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-220">
    <a href="">
        Link Two
        </a>
    </li>
</ul>

So far I’m trying the $link_before parameter but its generating both of them at the same time, meaning its doing <img id="icon-one" /><img id="icon-two" /> in the middle of the <a> tag.

Now I’m looking at walkers, but I’m wondering if there’s a clearer way to do it, and how?

Related posts

Leave a Reply

2 comments

  1. I would probably go with a pure CSS solution and apply the image as a background image. So something like this:

    #main-menu > li.menu-item:nth-child(1) > a {
        /* 1st background image here */
    }
    #main-menu > li.menu-item:nth-child(2) > a {
        /* 2nd background image here */
    }
    

    No need to mess with the PHP code for a simple display issue.

  2. Options panel in menu editing

    enter image description here

    In WordPress menu admin, you can specify a css class for each menu item. This way you can use background-image css property to customize each menu item. The menu is then rendered like this :

    <ul id="main-menu">
        <li id="menu-item-219" class="icon-one menu-item menu-item-type-taxonomy menu-item-object-category menu-item-219">
            <a href="">
                Link One
            </a>
        </li>
        <li id="menu-item-220" class="icon-two menu-item menu-item-type-taxonomy menu-item-object-category menu-item-220">
        <a href="">
            Link Two
            </a>
        </li>
    </ul>
    

    And you can do something like this for CSS :

    #main-menu .icon-one {
       background:url('../img/icon-one.jpg') no-repeat 0 0;
       padding: 0 0 0 50px; // depending on your icon
    }
    
    #main-menu .icon-two {
       background:url('../img/icon-two.jpg') no-repeat 0 0;
       padding: 0 0 0 50px; // depending on your icon
    }
    

    NB : If you don’t see the css option in the menu item admin block, check it in the option panel on top right.