提问者:小点点

如何在WordPress中获取菜单项?


我想获得我的wp主菜单项。我试过一些代码,但都是空白页。我不知道我必须使用哪种方法,也不知道是否需要在我的页面中包含任何其他页面?

有没有办法直接从数据库中获取菜单项,而不使用wp方法和函数?我现在不能理解wp的表结构。所以我不知道表之间的确切关系。

谢谢


共3个答案

匿名用户

如果您知道菜单位置id(通常在functions.php中通过“register\u nav\u 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...
        }
}

这里是关于所有nav_menu数据的链接,您可以通过mysql请求直接从数据库中选择:http://lasota.community.uaf.edu/2011/07/29/nav-menu-data-location-in-wordpress-3-2/

匿名用户

你可以试试这个

$menu_name = 'sidebar-menu'; //menu slug
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );

echo "<pre>";
print_r($menuitems);
echo "</pre>";

您将获得菜单对象

参考:http://wiki.workassis.com/wordpress-get-menu-array/

匿名用户

<?php 
$menu = 'menu-name/menu-id';
$args = array(
        'order'                  => 'ASC',
        'orderby'                => 'menu_order',
        'post_type'              => 'nav_menu_item',
        'post_status'            => 'publish',
        'output'                 => ARRAY_A,
        'output_key'             => 'menu_order',
        'nopaging'               => true,
        'update_post_term_cache' => false );
$items = wp_get_nav_menu_items( $menu, $args ); 
?>