我想获取我的wp主菜单中的项目.我尝试了一些代码,但所有代码都只返回空白页.我不知道我必须使用哪种方法,也不知道需要在页面中包含其他页面吗?
还有什么方法可以直接从数据库中获取菜单项,而无需使用wp方法和函数?我暂时不了解wp的表结构.所以我不完全知道表之间的关系.
谢谢.
解决方法:
如果您知道菜单的位置ID(通常在functions.php中由“ register_nav_menus”声明),则可以使用以下代码段:
// GET ALL MENU OBJECTS AT SPECIFIED LOCATION
function yourprefix_get_menu_items($location_id){
//$locations = get_registered_nav_menus();
$menus = wp_get_nav_menus();
$menu_locations = get_nav_menu_locations();
if (isset($menu_locations[ $location_id ]) && $menu_locations[ $location_id ]!=0) {
foreach ($menus as $menu) {
if ($menu->term_id == $menu_locations[ $location_id ]) {
$menu_items = wp_get_nav_menu_items($menu);
break;
}
}
return $menu_items;
}
}
或更多来自法典的简短版本:
function yourprefix_get_menu_items($menu_name){
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
return wp_get_nav_menu_items($menu->term_id);
}
}
然后使用此数组执行您想要的所有操作,如下所示:
$menu_items = yourprefix_get_menu_items('sidebar-menu'); // replace sidebar-menu by desired location
if(isset($menu_items)){
foreach ( (array) $menu_items as $key => $menu_item ) {
...some code...
}
}
标签:php,wordpress,menu
来源: https://codeday.me/bug/20191010/1884794.html
该博客介绍了如何在WordPress中通过PHP代码获取指定位置的菜单项。如果知道菜单的位置ID,可以使用提供的代码段来获取菜单项,避免空白页问题。这涉及到`wp_get_nav_menu_items`和`wp_get_nav_menu_object`等WordPress函数。
685

被折叠的 条评论
为什么被折叠?



