如何在菜单中更改自定义项目顺序

时间:2014-02-12 15:49:01

标签: php wordpress function menu

您好我的网站有一个主菜单

Home | How to start | about | contact | categories

但我添加了一个列出functions.php

中所有类别的项目
add_filter('wp_nav_menu_items', 'category_list', 10, 2);
function category_list($items, $args)
{
    if( $args->theme_location == 'header' )
    {
        $items .= '<li id="menu-item-184" class="parent menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-184"><a href=""#"">Kategorie</a><ul class="sub-menu">';
        $categories = get_categories();
        foreach ($categories as $category)
        {
            $option = '<li><a href="'.get_category_link( $category->term_id ).'">';
            $option .= $category->cat_name;
            $option .= '</a></li>';
            $items .= $option;
        }

        $items .= '</ul></li>';
    }
    return $items;
}
How 

如何更改此项目的顺序。我在Appearance-&gt;菜单中看不到它我希望将它移动到菜单中的第二个位置。

Home | Categories | How to start | about | contact

1 个答案:

答案 0 :(得分:0)

我使用了一种解决方法,可能对您的情况有用。我使用customItem变量而不是项来构建自定义菜单项。然后我将原始菜单拆分成一个数组。创建了一个计数器,以正确的顺序添加自定义菜单项。

function category_list($items, $args)
{
    if( $args->theme_location == 'header' )
    {
        $customitem .= '<li id="menu-item-184" class="parent menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-184"><a href=""#"">Kategorie</a><ul class="sub-menu">';
        $categories = get_categories();
        foreach ($categories as $category)
        {
            $option = '<li><a href="'.get_category_link( $category->term_id ).'">';
            $option .= $category->cat_name;
            $option .= '</a></li>';
            $customitem .= $option;
        }

        $customitem.= '</ul></li>';

        //Here is the ordering part:
         $newMenu='';
         $originalMenu=explode("</li>",$items);
         $count=0;
         foreach($originalMenu as $orgMenuItem){
            $count++;
            if($count==2) $newMenu.= $customitem;
            $newMenu.= $orgMenuItem.'</li>';
         }
         $items=$newMenu;


    }
    return $items;
}