insert element inside wp menu list item

I am not sure if it is clear from the title what I want to achieve here so let me try to clarify this.

I wanna make use of WordPress’s menu system and need to adjust it to my needs, which means that I need it to go from here:

Read More
<ul>
<li>item1</li>
<li>item2</li>
etc.
</ul>

to here:

<ul>
<li><div>1(dynamic-content)</div>item1</li>
<li><div>2(dynamic-content)</div>item2</li>
etc.
</ul>

What would be the best way to achieve this?? Just need some quick directions to go there and do it myself without losing too much time finding appropriate solution.

Is it the wp_nav_menu() or wp_get_nav_menu_items() that I should be researching? Short sample would be appreciated as well if it’s not too much to ask.
And another thing.. I would appreciate tip on how to generate number inside that inserted div that represents menu item’s order apperance: 1,2,3,etc. Is there a way to pick up this from WordPress’s core?

Thank you so much. Any help appreciated.

Related posts

Leave a Reply

1 comment

  1. You could use a custom walker or just filter the menu title. It depends on the position you need for your extra content: Should it appear before or inside the link?

    Example with a walker

    Update: Actually, this cannot work: the parent function creates the <li, so you have to copy and adjust the whole parent function.

    wp_nav_menu(
        array (
            'walker' => new WPSE_45647_Walker
        )
    );
    
    class WPSE_45647_Walker extends Walker_Nav_Menu
    {
        public function start_el( &$output, $item, $depth, $args )
        {
            $output .= $this->custom_content( $item );
            parent::start_el( &$output, $item, $depth, $args );
        }
    
        /**
         * Create your extra content here.
         * @return string
         */
        protected function custom_content( $item )
        {
            // inspect the item and return your 
            // custom content as a string
        }
    }
    

    Example with a filter

    More hackish, but maybe easier to understand: Grab the <li> and replace <a with $custom <a

    add_filter( 'walker_nav_menu_start_el', 'wpse_45647_add_custom_content', 10, 2 ); 
    function wpse_45647_add_custom_content( $item_output, $item )
    {
        static $counter = 0; 
        // You may inspect $item and do something more creative here.
        $custom = ++$counter . ' Hello World!'; 
        return str_replace( '<a ', $custom . '<a ', $item_output );
    }