0

I have added this code in function.php to retrieves menu and converts it to a readable array but It's not working and give me this warning. Warning : Invalid argument supplied for foreach() in C:\xampp\htdocs\Upwork\wp-content\themes\truckloanhub\functions.php on line 117

Warning : Invalid argument supplied for foreach() in C:\xampp\htdocs\Upwork\wp-content\themes\truckloanhub\functions.php on line 127

function wp_get_menu_array($current_menu) {



$array_menu = wp_get_nav_menu_items($current_menu);
   $menu = array();
   foreach ($array_menu as $m) {
       if (empty($m->menu_item_parent)) {
           $menu[$m->ID] = array();
           $menu[$m->ID]['ID']      =   $m->ID;
           $menu[$m->ID]['title']       =   $m->title;
           $menu[$m->ID]['url']         =   $m->url;
           $menu[$m->ID]['children']    =   array();
       }
   }
   $submenu = array();
   foreach ($array_menu as $m) {
       if ($m->menu_item_parent) {
           $submenu[$m->ID] = array();
           $submenu[$m->ID]['ID']       =   $m->ID;
           $submenu[$m->ID]['title']    =   $m->title;
           $submenu[$m->ID]['url']  =   $m->url;
           $menu[$m->menu_item_parent]['children'][$m->ID] = $submenu[$m->ID];
       }
   }
   return $menu;

}

1
  • $array_menu = wp_get_nav_menu_items($current_menu); may be the problem; have you run a var_dump($array_menu) to make sure you're getting what you expected? Jan 23 at 3:34
1

The bug is not in this snippet of code. The problem is with how you call wp_get_nav_menu_array, wherever that happens. The $current_menu is likely something invalid, so wp_get_nav_menu_items returns false, and thus you get the error that you get.

You can see in user contributed notes an example of how to get a valid value for $current_menu https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/#user-contributed-notes

1
  • Can you give me a sample code to get $current menu? Jan 22 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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