Search code examples
phpprestashopprestashop-1.7

Ordering categories alphabetically in Prestashop top menu


I have set up a Prestashop 1.7 website for a client and I'm importing his new products with a script every day. These products are put in categories that I create if they don't yet exist. My problem is that the newly created categories are put at the end of the drop down top menu, and it would be much better to have them displayed alphabetically. I know I can do that in the back office by drag and dropping them in place, but I want my script to do it automatically.

I've already overriden the Category.phpclass to make other changes so I can edit this file. I tried to change every ORDER BY clauses I found from depth or position to name. It had some effects as categories were indeed sorted by name but a lot of them simply disappeared from the menu (i.e. out of say 10 categories sorted by position, only 4 remained sorted by name).

Do you know a way to achieve this?


Solution

  • You can do this 2 ways. My approach is to do this when the menu is created, this way it's sorted in every language. To do so, just use this override for ps_mainmenu module:

    use PrestaShop\PrestaShop\Core\Module\WidgetInterface;
    
    class Ps_MainMenuOverride extends Ps_MainMenu implements WidgetInterface
    {
        protected function generateCategoriesMenu($categories, $is_children = 0)
        {
            $categories = $this->sortCategories($categories);
            return parent::generateCategoriesMenu($categories, $is_children);
        }
    
        public function sortCategories($categories)
        {
    
            uasort($categories, 'cmpcat');
    
            foreach($categories as $k => $category)
            {
                if (isset($category['children']) && !empty($category['children'])) {
                    $children = $this->sortCategories($category['children']);
                    $categories[$k]['children'] = $children;
                }
            }
            return $categories;
        }
    }
    
    function cmpcat($a, $b) {
        return strcmp($a['name'], $b['name']);
    }
    

    The other option is to sort when creating the menu. But I would have to see the current import code, and even then could be more difficult.

    This is for the children categories. For the main categories it would be necessary to override another function.