How to add submenu items programmatically in WordPress?

How to add submenu items programmatically in WordPress?

17 December 2021

Appending an item to the existing menu can be done using the wp_nav_menu_objects hook. The submenu can be created using the current menu structure.

In the submenu code snippet, we need to add the specific ID to become the child of the specific menu.

There are specific requirements we need to follow to include the items in the submenu. The requirements are defined in the array and the array which include the title for the submenu, Unique ID, Parent menu item, URL for redirection.

Code Snippet

The snippet is to be added in the functions.php

add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );
 function ravs_add_menu_parent_class( $items ) {
    foreach ( $items as $item ) {
         print_r($item);//print each menu item an get your parent menu item-id
    }
   $link = array (
       'title'            => 'add your menu title here',
       'menu_item_parent' =>add here parent menu item,
       'ID'               => 'add here unique ID',
       'url'              => 'www.google.com'
  );
  $items[] = (object) $link;
  return $items;
}

Request a quote