Using WP3 Menu

July 21st, 2010 |

Finally, the WP’s authors have implemented a such required functionality, as the menu! In this article, I described how to work with it and what problems you might encounter.

1. You should register “menu locations” with using register_nav_menus function.

register_nav_menus(array(
    'primary' => __('Primary', 'nix'),
));

2. Do not forget about the utility parameters of wp_nav_menu function.

wp_nav_menu(array( 
    'depth' => 2,                  // levels of the hierarchy are to be included
    'theme_location' => 'primary', // the location in the theme to be used. see 1
    'menu_class' => 'header_menu', // CSS class to use for the <UL> element 
    'container' => false           // turning off the excess wrapper
)); 

3. Checking for specified menu to the location – see 1.

has_nav_menu('primary');

4. If the user does not set a menu for location, then arises extra wrapper.

if (has_nav_menu('primary')) {
    wp_nav_menu( array( 
        'depth' => 1, 'container' => false, 
        'theme_location' => 'primary', 
        'menu_class' => 'header_menu') );
}
else {
    echo '<ul class="header_menu">';
    wp_list_pages( array('depth' => 1, 'title_li' => '' ));
    echo '</ul>';
}

5. Add a choice of a menu in an arbitrary place back-end.

    <select name="">
        <option value="0">- Select -</option>
        <?php $_nav_menus = wp_get_nav_menus( array('orderby' => 'name') );
        foreach( $_nav_menus as $index => $_nav_menu ) { ?>
        <option value="<?php echo attribute_escape($_nav_menu->term_id) ?>" 
             <?php if ($_nav_menu->term_id == get_option('some_menu')) 
                echo 'selected="selected"' ?> >
             <?php echo attribute_escape($_nav_menu->name) ?>
        </option>
        <?php } ?>
    </select>

And displaying this menu:

if (is_nav_menu(get_option('some_menu'))) {
    wp_nav_menu( array( 
        'menu' => get_option('some_menu'), 
        'depth' => 1, 'container' => false, 
        'menu_class' => 'header_menu') );
}

6. Print url of first menu item:

$locations = get_nav_menu_locations();
if (isset($locations['**menu-location**'])){
    $menu = wp_get_nav_menu_object( $locations['**menu-location**'] );
    $menu_items = wp_get_nav_menu_items($menu->term_id);
    if (count($menu_items)) {
        echo $menu_items[0]->url;
    }
}

There are no comments yet

Leave a Reply

Your email address will not be published. Required fields are marked *

*