How to automatically add counted number to navigation menu items?


In my website I need a navigation menu to show arrangement of my posts. So I need the navigation menu to count the items and display the number of every item as a label before the title of that item. I think we need a foreach in wp_get_nav_menu_items to count but I don’t know exactly the way.
I need something like this from that menu:
1- title one
2- title two
3- title three
4- …

I have the following codes but I have two issues:
1- I do not know why it does not work?
2- I need a class as .current-menu-item to find the current item in other items. this class is as a default class in wordpresss menu but I can not do that.

// Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu)
// This code based on wp_nav_menu's code to get Menu ID from menu slug
$menu_name = 'custom_menu_slug';

if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
    $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );

    $menu_items = wp_get_nav_menu_items($menu->term_id);

    $menu_list = '<ul id="menu-' . $menu_name . '">';

    menu_count = 0;
    foreach ( (array) $menu_items as $key => $menu_item ) {
        $title = $menu_item->title;
        $url = $menu_item->url;
        $menu_list .= '<li><span>'.$menu_count.'</span><a href="' . $url . '">' . $title . '</a></li>';
    $menu_list .= '</ul>';
} else {
    $menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
// $menu_list now ready to output

Thanks a lot to helping


>>> Share a link to this question, just copy and paste the code bellow on your web page <<<

<a href="">

How to automatically add counted number to navigation menu items?</a>
, , Sh.Dehnavi 7 months 0 Answers 38 views 0

Leave an answer