Arbitrary view of the arbitrary menu


Good time to all fans of the wonderful WordPress engine! Today we are talking about such a powerful tool as an arbitrary menu. This new feature appeared not so long ago, since version 3.0, and very quickly gained popularity among the site builders. Enable support for arbitrary menus in your theme is very simple, you need to add the following lines to the function.php file:

if (function_exists('add_theme_support')) {
    add_theme_support('menus');
}

After that, in the Appearance tab, a new menu item appears, where everything is quite intuitive. The function wp_nav_menu () is responsible for calling the menu in the right places of the template, which can be fine tuned, but often it happens that the output The menu should differ materially from the proposed ul list. For example, items should be displayed inside div blocks or a unique class must be assigned to the last item. For this we propose to use our own output variant by adding the custom_menu () function internally function.php:


function custom_menu($menu_name) {

	$menu = wp_get_nav_menu_object($menu_name);
	$menu_items = wp_get_nav_menu_items($menu->term_id);

	$menu_list = '<ul id="menu">';
	foreach ( (array) $menu_items as $key => $menu_item ) {
	    $title = $menu_item->title;
	    $url = $menu_item->url;
	    $menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
	}
	$menu_list .= '</ul>';
        echo $menu_list;

}

As you can see, in this function you can easily change the html output code. And if you need to add a unique class to a particular item, then add a counter:

function custom_menu($menu_name) {

	$menu = wp_get_nav_menu_object($menu_name);
	$menu_items = wp_get_nav_menu_items($menu->term_id);
        $count = count($menu_items);
        $i = 0;

	$menu_list = '<ul id="menu">';
	foreach ( (array) $menu_items as $key => $menu_item ) {
            $i++; 
            if($i == $count){
               $class = " class='none'";
            } else {
               $class = "";
            }
	    $title = $menu_item->title;
	    $url = $menu_item->url;
	    $menu_list .= '<li'.$class.'><a href="' . $url . '">' . $title . '</a></li>';
	}
	$menu_list .= '</ul>';
        echo $menu_list;

}

The function is called in the standard way – with the name of the menu as an argument, for example

custom_menu("Top Menu");

We hope for the usefulness of this information for you. Until next time!


Требуется подобная доработка? Напишите нам.


Name

Email


Website


Messagge