如何在Wordpress中获取菜单项? [英] How to Get Menu Items In Wordpress?
问题描述
我想获取wp主菜单中的项目.我尝试了一些代码,但所有代码都只返回空白页.我不知道我必须使用哪种方法,也不知道需要在页面中包含其他页面吗?
I want to get items of my wp primary menu. I tried some code but all of them are returns only blank page. I don't know which method I must use and don't know need include any other page to my page?
还有什么方法可以直接从数据库中获取菜单项,而无需使用wp方法和函数?我暂时不了解wp的表结构.所以我不确切地知道表之间的关系.
And Is there any way to get menu items from database directly without using wp methods and functions? I couldn't understand table structure of wp for now. So I don't know relationships between tables exactly.
谢谢.
推荐答案
如果您知道菜单的位置ID(通常在"functions.php"中由"register_nav_menus"声明),则可以使用以下代码段:
If you know your menu location id (usually declared in functions.php by "register_nav_menus") you can use this snippet:
// 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;
}
}
或来自法典的其他简短版本:
Or more short version from codex:
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);
}
}
然后使用该数组完成您想要的所有事情,如下所示:
Then do everything you want with this array like so:
$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...
}
}
这是有关所有nav_menu数据的链接,您可以通过mysql请求直接从数据库中选择这些数据: http://lasota.community.uaf.edu/2011/07/29/nav-menu-data-location-in-wordpress-3-2/
And here is link about all nav_menu data which you can select directly from database by mysql request: http://lasota.community.uaf.edu/2011/07/29/nav-menu-data-location-in-wordpress-3-2/
这篇关于如何在Wordpress中获取菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!