0

The should be simple but I just can't figure it out nor find an answer. I need to add a data-id attribute to the <li> parent container of the respective child page <a> links.

The HTML is as follows:

  <aside id="sidebar-b">
    <ul class="sub-menu side-nav page-sidebar child-pages">
      <li id="menu-item-9044" class="menu-item menu-item-type-post_type menu-item-object-post current-menu-item menu-item-9044">
        <a href="http://localhost/about/" class="menu-image-title-after">
          <span class="menu-image-title">About</span>
        </a>
      </li>
      <li id="menu-item-9045" class="menu-item menu-item-type-post_type menu-item-object-post current-menu-item menu-item-9045">
        <a href="http://localhost/contact/" class="menu-image-title-after">
          <span class="menu-image-title">Contact</span>
        </a>
      </li>
      <li id="menu-item-9046" class="menu-item menu-item-type-post_type menu-item-object-post current-menu-item menu-item-9046">
        <a href="http://localhost/history/" class="menu-image-title-after">
          <span class="menu-image-title">History</span>
        </a>
      </li>
    </ul>
  </aside>

It should be noted that, as a temporary solution, I'm using jQuery to manually move the child page list out from its parent into #sidebar-b.

Any advice would be much appreciated!

1 Answer 1

2

Assuming that your html is outputted by a wordpress menu sitting in a sidebar, you have to extend the Walker_Nav_Menu Class which is used by menu template functions like wp_nav_menu. As stated in the reference of wp_nav_menu, you could modify its output like:

class My_DataId_Walker_Nav_Menu extends Walker_Nav_Menu {

    //  other code found in original Walker_Nav_Menu class

    //  changing output of li elemens
    $output .= $indent  
            .  '<li id="nav-menu-item-' . $item->ID . '" '
            .  'data-id="' . $item->ID . '" ' 
            .  'class="' . $depth_class_names . ' ' . $class_names . '">';

    //  other code found in original Walker_Nav_Menu class

}

//  in the template file, output menu with custom walker class
wp_nav_menu( 
    array(
        'theme_location'    =>'primary', // your menu position
        'walker'            => new My_DataId_Walker(),
        'depth'             => 0
    ) 
);
1
  • Fairly certain I didn't do it the proper way but I was able to get it working. Ultimately, I copied the the start_el function and added data-id="'.url_to_postid($item->url).'" to the $output. If there's a more efficient means to achieve this result I am all ears. The menu is being outputted not from custom widget sidebar called #top-b.
    – DaveyJake
    Commented Nov 24, 2015 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.