Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

This question already has an answer here:

I'm trying to figure out if it's possible to attach an attribute to a wp nav menu item.
To demonstrate, this php:

<?php
    wp_nav_menu(array(
    'menu'  =>  'main',
    'container' => false
));
?>

would output a menu like so:

<ul id="menu-main" class="menu">
<li id="menu-item-01" class="menu-item">Menu 01</li>
<li id="menu-item-02" class="menu-item">Menu 02</li>
<li id="menu-item-03" class="menu-item">Menu 03</li>
<li id="menu-item-04" class="menu-item">Menu 04</li>
</ul>

but what I'd actually like is something like this:

<ul id="menu-main" class="menu">
<li id="menu-item-01" class="menu-item" data-hook="01">Menu 01</li>
<li id="menu-item-02" class="menu-item" data-hook="02">Menu 02</li>
<li id="menu-item-03" class="menu-item" data-hook="03">Menu 03</li>
<li id="menu-item-04" class="menu-item" data-hook="04">Menu 04</li>
</ul>

Is that at all possible to achieve? The attribute doesn't have to be data-hook I'm just using that as an example, just something I can use as an identifier.

share|improve this question
add comment

marked as duplicate by toscho Jun 18 '13 at 12:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

up vote 0 down vote accepted

You can use a Custom Walker to add attributes to the menu items.

Basically, you add a parameter 'walker' to the wp_nav_menu() options and call an instance of an enhanced class:

wp_nav_menu(
    array (
        'menu'            => 'main-menu',
        'container'       => FALSE,
        'container_id'    => FALSE,
        'menu_class'      => '',
        'menu_id'         => FALSE,
        'depth'           => 1,
        'walker'          => new Description_Walker
    )
);

The class Description_Walker extends Walker_Nav_Menu and changes the function start_el( &$output, $item, $depth, $args ).

  1. From the Codex:
    http://codex.wordpress.org/Function_Reference/wp_nav_menu#Using_a_Custom_Walker_Function

  2. I found this tutorial, you might find it very useful:
    http://www.kriesi.at/archives/improve-your-wordpress-navigation-menu-output

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.