As the title says, I'm trying to populate my main menu from an external JSON API that changes quite frequently, so I need the entire menu to be dynamic. I managed to insert the API like this:
$content = file_get_contents( 'https://www.motobuykers.es/apih/menus/desktop/' ); $json = json_decode( $content ); $menuname = 'Test'; $menulocation = 'primary'; // Does the menu exist already? $menu_exists = wp_get_nav_menu_object( $menuname ); // If it doesn't exist, let's create it. if ( ! $menu_exists ) { $menu_id = wp_create_nav_menu( $menuname ); foreach ( $json->_embedded->menuitem as $menuitem ) { wp_update_nav_menu_item( $menu_id, 0, array( 'menu-item-title' => $menuitem->title, 'menu-item-classes' => $menuitem->class, 'menu-item-url' => $menuitem->url, 'menu-item-status' => 'publish' ) ); } if ( ! has_nav_menu( $menulocation ) ) { $locations = get_theme_mod( 'nav_menu_locations' ); $locations[ $menulocation ] = $menu_id; set_theme_mod( 'nav_menu_locations', $locations ); } }
The problem with this code is that once I make the menu, I can no longer update it from the API. I've also tried to use Daggerhart's solution, but the foreach in the next snippet returns:
Warning: Invalid argument supplied for foreach()
Even though I pass the exact same JSON as the first snippet:
function custom_nav_menu_items( $items, $menu ) { // only add item to a specific menu if ( $menu->slug == 'menu-1' ) { //if (is_array($json->_embedded->menuitem)) { //if (is_array($values) || is_object($values)){ foreach ( $json->_embedded->menuitem as $menuitem ) { $items[] = _custom_nav_menu_item( $menuitem->name, $menuitem->url, addID() ); } return $items; } } add_filter( 'wp_get_nav_menu_items', 'custom_nav_menu_items', 20, 2 );
Any ideas?