正如标题所述,我试图从一个经常更改的外部JSON API填充我的主菜单,因此我需要整个菜单是动态的。我成功地插入了如下API:
$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 );
}
}
这段代码的问题是,一旦我创建了菜单,就不能再从API更新它了。我也试着
use Daggerhart\'s solution, 但下一个代码段中的foreach返回:
警告:为foreach()提供的参数无效
尽管我传递的JSON与第一个片段完全相同:
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 );
有什么想法吗?