insert element inside wp menu list item

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 );
}

Leave a Comment