Counter - Inside Menu Links
You can e.g. use the nav_menu_item_title
Codex filter to adjust the menu titles:
add_filter( 'nav_menu_item_title', function( $title, $item, $args, $depth )
{
static $instance = 0;
// Append an increasing numbercounter to the menu title for menu items
// within a given menu location and menu class
if( 'my-custom-location' === $args->theme_location
&& in_array( 'my-custom-class', (array) $item->classes )
)
$title .= sprintf( ' <span>%d<<span class="counter">%d</span>', ++$instance );
return $title;
}, 10, 4 );
where you should adjust it to your theme location and menu class.
Counter - Outside Menu Links
The above approach will add the counter within the link title. What if we want to add it right after the menu link? Then we can use the walker_nav_menu_start_el
Codex filter:
add_filter( 'walker_nav_menu_start_el', function( $item_output, $item, $depth, $args )
{
static $instance = 0;
// Append an increasing counter to the menu link for menu items
// within a given menu location and menu class
if( 'my-custom-location' === $args->theme_location
&& in_array( 'my-custom-class', (array) $item->classes )
)
$item_output .= sprintf( ' <span class="counter">%d</span>', ++$instance );
return $item_output;
}, 10, 4 );
Note on the inline documentation
I noticed that the inline documentation for the nav_menu_item_title
says $args
is an array but it seems to be a stdClass
object. So this is somewhat confusing!
If we check out Walker::display_element()
then we see that the $args
input argument is in fact an array, that becomes merged to the array of the output, element and depth with:
$cb_args = array_merge( array(&$output, $element, $depth), $args);
call_user_func_array(array($this, 'start_el'), $cb_args);
But here $cb_args
is an array where the fourth element is a stdClass
object (not an array) and this is the fourth input argument of the Walker_Nav_Menu::start_el()
method.
The inline documentation for Walker_Nav_Menu::start_el()
also says that it's third input argument is an array. when it's an object.
I will consider creating a trac ticket for this.