2
votes

I have the following menu structure in WordPress:

  • Parent 1
    • Submenu 1
    • Submenu 2
    • Submenu 3
  • Parent 2
    • Submenu 4
    • Submenu 5
  • Parent 3
    • Submenu 6

I am using the WordPress wp_nav_menu_objects filter to retrieve all submenu items. Which I have got to work with the code bellow:

add_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 );

// filter_hook function to react on sub_menu flag
function my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) {


  if ( isset( $args->sub_menu ) ) {

    foreach ( $sorted_menu_items as $key => $item ) {

      if ( $item->menu_item_parent == '0' ) { // only get sub-menu items
        unset( $sorted_menu_items[$key] );
      }

    }

    return $sorted_menu_items;

  } else {
    return $sorted_menu_items;
  }
}

Too display the Nav:

wp_nav_menu( array(
    'theme_location' => 'main-menu',
    'menu_id' => 'sub-menus',
    'menu_class'=>'menu',
    'container'=>'ul',
    'sub_menu' => true,
) );

Which results in the HTML:

<ul>
  <li>Submenu 1</li>
  <li>Submenu 2</li>
  <li>Submenu 3</li>
  <li>Submenu 4</li>
  <li>Submenu 5</li>
  <li>Submenu 6</li>
</ul>

Ideally I would like each submenu "group" to be in its own <ul> container, but I can't seem to figure out how this can be done. Bellow is an example of the preferred result.

<ul>
  <ul>
    <li>Submenu 1</li>
    <li>Submenu 2</li>
    <li>Submenu 3</li>
  </ul>
  <ul>
    <li>Submenu 4</li>
    <li>Submenu 5</li>
  </ul>
  <ul>
    <li>Submenu 6</li>
  </ul>
</ul>

Any advice on how to approach this problem would be greatly appreciated!

2

2 Answers

0
votes

You can't insert html, as Wordpress handles the result. But, you could insert some code in the for loop to create an array of just html. The text and links for each entry can then be passed to whatever code you want to process it with.

So, you would replace the unspec statement in the loop with code to build an array with just html, as in your example of desired output. You would also create a new parm to handle this new array.

0
votes

You can add another parm to $args passed to the filter. In this case, it will be an array, which will hold the html. You did it with $args -> sub_menu in your current code, and you reference it with the isset statement.