Check if menu id = $specific_id – then insert specific <img>

I currently have a menu structure as followed:

<ul class="level-1" id="menu-menu1">
  <li id="menu-item-411">
    <a href="http://www.link.com">Frontpage</a>
  </li>
  <li id="menu-item-425"></li>
  <li id="menu-item-80"></li>
</ul>

What im looking to do is hardcore a little menu icon image for each different menu id, however im not sure how to manipulate wp_nav_menu to insert something “custom” like this? Ideally what I want to do is something like: if($menu_id == 411) { //insert specific <img>– with some result like this:

Read More
  <li id="menu-item-411">
    <img src="my-specific-img-for-this-menu-id.gif" />
    <a href="http://www.link.com">Frontpage</a>
  </li>

Right now my menu is printed out with:

                    $nav_args = array(
                        'theme_location' => 'nav',
                        'container' => 'none',
                        'menu_class' => 'level-1',
                        'depth' => 3,   
                    );

                    wp_nav_menu( $nav_args );

Any ideas?

Related posts

2 comments

  1. Creating a custom Walker is a valid way to solve this, and is the first thing that crossed my mind, but it is not strictly necessary. It is possible to pull this off with filters, albeit by mildly abusing one of them 🙂

    Proof of concept:

    function insert_image_wpse_130477($item_output) {
        remove_filter('walker_nav_menu_start_el','insert_image_wpse_130477');
        $prepend = apply_filters('my_item_prepend','');
        return $prepend.$item_output;
    }
    
    function check_id_wpse_130477($id, $item, $args) {
      if ('menu-item-6' == $id) { // edit for your circumstances
        add_filter(
          'my_item_prepend',
          function() use ($id) {
            // add logic to conditionally add your images based on the ID
            return '##'.$id.'##';
          }
        );
        add_filter(
          'walker_nav_menu_start_el',
          'insert_image_wpse_130477'
        );
      }
      return $id;
    }
    add_filter('nav_menu_item_id','check_id_wpse_130477',1,3);
    

    I can think of several other ways to do this– a class, for example, or a single more complicated callback and a static variable– but this is probably the easiest to follow.

  2. You need to do a custom walker on the menu (link) which allows you to rewrite the navigation code to your needs.

Comments are closed.