1 回答
TA贡献1797条经验 获得超6个赞
编辑:
要解决重复的情况,您必须添加一行代码。您可以根据要选择的父链添加以下行之一。我还在实际代码中添加了这些行,以向您展示它们的去向。
// Get First Parent Chain
$current_level = array_values(array_slice($current_level, 0, 1));
// Get Last Parent Chain
$current_level = array_values(array_slice($current_level, -1, 1));
原始答案:(也更新了以上几行)
此代码将为您提供所有级别的项目,它仅根据您的要求编写了三个级别,但您可以使用该逻辑并根据需要将代码重复到多个级别,或者最好编写一些递归的内容。
$menu_name = 'topnav';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items( $menu->term_id );
// Convert Objects to Arrays, Enables us to use Array Filter
$json = json_encode($menu_items);
$menu_items = json_decode($json, true);
// Current Page
$child = get_the_id();
$current_level = array_filter( $menu_items, function($v, $k) use ($child) {
return $v['object_id'] == $child;
}, ARRAY_FILTER_USE_BOTH );
// Get First Parent Chain ( Uncomment below line if you want to use this )
//$current_level = array_values(array_slice($current_level, 0, 1));
// Get Last Parent Chain ( Uncomment below line if you want to use this )
//$current_level = array_values(array_slice($current_level, -1, 1));
$current_level_keys = array_keys($current_level);
$parent = $current_level[$current_level_keys[0]]['menu_item_parent'];
if( !empty( $parent ) )
{
$current_level_items = array_filter( $menu_items, function($v, $k) use ($parent) {
return $v['menu_item_parent'] == $parent;
}, ARRAY_FILTER_USE_BOTH );
} else {
$current_level_items = $current_level[$current_level_keys[0]];
}
echo '<pre>';
print_r($current_level_items);
echo '</pre>';
$parent_level = array_filter( $menu_items, function($v, $k) use ($parent) {
return $v['ID'] == $parent;
}, ARRAY_FILTER_USE_BOTH );
$parent_level_keys = array_keys($parent_level);
$grand_parent = $parent_level[$parent_level_keys[0]]['menu_item_parent'];
if( !empty( $grand_parent ) )
{
$parent_level_items = array_filter( $menu_items, function($v, $k) use ($grand_parent) {
return $v['menu_item_parent'] == $grand_parent;
}, ARRAY_FILTER_USE_BOTH );
} else {
$parent_level_items = $parent_level[$parent_level_keys[0]];
}
echo '<pre>';
print_r($parent_level_items);
echo '</pre>';
$grand_parent_level = array_filter( $menu_items, function($v, $k) use ($grand_parent) {
return $v['ID'] == $grand_parent;
}, ARRAY_FILTER_USE_BOTH );
$grand_parent_level_keys = array_keys($grand_parent_level);
$great_grand_parent = $grand_parent_level[$grand_parent_level_keys[0]];
echo '<pre>';
print_r($great_grand_parent);
echo '</pre>';
}
我试图将其写成自我解释,但如果您有任何问题,我将很乐意提供帮助。
- 1 回答
- 0 关注
- 167 浏览
添加回答
举报