marcin.g
marcin.g

Reputation: 365

How to change custom item order in menu

Hello I have a main menu in my website

Home | How to start | about | contact | categories

but I add one item that lists all categories in 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 

How I can change the order of this item. I can't see it in Appearance->menu I want to move it to second position in menu.

Home | Categories | How to start | about | contact

Upvotes: 1

Views: 1165

Answers (1)

Kuzgun
Kuzgun

Reputation: 4737

I used a workaround, might be useful in your case. I used customItem variable instead of items to build the custom menu item. Then I split the original menu into an array. Created a counter to add the custom menu item in the correct order.

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;
}

Upvotes: 1

Related Questions