我创建了一个使用foreach将数据存储在数组中的函数(在本例中为wordpress菜单项):
public function beratungmenu()
{
$array_menu = wp_get_nav_menu_items("205");
$beratungmenu = array();
foreach ($array_menu as $m) {
if (empty($m->menu_item_parent)) {
$beratungmenu[$m->ID] = array();
$beratungmenu[$m->ID]['ID'] = $m->ID;
$beratungmenu[$m->ID]['title'] = $m->title;
$beratungmenu[$m->ID]['url'] = $m->url;
$beratungmenu[$m->ID]['postid'] = get_post_meta( $m->ID, '_menu_item_object_id', true );
$beratungmenu[$m->ID]['desc'] = get_field('menu_item_desc', $m);
$beratungmenu[$m->ID]['icon'] = get_field('fa_icon_name', get_post_meta( $m->ID, '_menu_item_object_id', true ));
}
}
$this_menu = wp_get_nav_menu_object("205");
$beratungmenu['menu_title'] = $this_menu->name;
return $beratungmenu;
}
public function institutmenu()
{
$array_menu = wp_get_nav_menu_items("206");
$institutmenu = array();
foreach ($array_menu as $m) {
if (empty($m->menu_item_parent)) {
$institutmenu[$m->ID] = array();
$institutmenu[$m->ID]['ID'] = $m->ID;
$institutmenu[$m->ID]['title'] = $m->title;
$institutmenu[$m->ID]['url'] = $m->url;
$institutmenu[$m->ID]['postid'] = get_post_meta( $m->ID, '_menu_item_object_id', true );
$institutmenu[$m->ID]['icon'] = get_field('fa_icon_name_institut', get_post_meta( $m->ID, '_menu_item_object_id', true ));
}
}
$this_menu = wp_get_nav_menu_object("206");
$institutmenu['menu_title'] = $this_menu->name;
return $institutmenu;
}
我在这里要做的就是为每个菜单创建一个单独的函数,这个函数不是很优雅,因为函数执行相同的操作,只是使用不同的数组名称。
出于学习目的,我试图找到一种方法来进一步抽象这个想法,只能让一个函数做同样的事情,传递菜单ID(" 205"和&# 34; 206"在示例中),检索菜单名称,根据菜单名称命名数组,然后执行上述功能。
这怎么可能?
答案 0 :(得分:0)
您可以像这样获取菜单:
public function getMenu($menuId, $fieldName)
{
$array_menu = wp_get_nav_menu_items($menuId);
$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]['postid'] = get_post_meta( $m->ID, '_menu_item_object_id', true );
$menu[$m->ID]['icon'] = get_field($fieldName, get_post_meta( $m->ID, '_menu_item_object_id', true ));
}
}
$this_menu = wp_get_nav_menu_object($menuId);
$menu['menu_title'] = $this_menu->name;
return $menu;
}
$beratungmenu = getMenu("205", "fa_icon_name");
$institutmenu = getMenu("206", "fa_icon_name_institut");