Last Updated: February 25, 2016
·
408
· danhanly

Magento: Anchor all Categories

Add the below to controller to one of your modules:

<?php

class Company_Module_Adminhtml_AnchorController extends Mage_Adminhtml_Controller_Action {

    public function indexAction() {
        $categories = Mage::getModel('catalog/category')
            ->getCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('entity_id', array("gt" => 1))
            ->setOrder('entity_id');

        $success = true;

        foreach ($categories as $category) {
            $success = $this->setAnchor($category);
            $success = $this->anchorChildren($category);
        }

        if ($success) {
            Mage::getSingleton('adminhtml/session')
            ->addSuccess("All Categories Set to Anchor");
        } else {
            Mage::getSingleton('adminhtml/session')
            ->addError("Anchor Process Failed for Some Categories");
        }
        $this->_redirectUrl($this->_getRefererUrl());
}

    protected function anchorChildren($category) {
        $children = $category->getChildrenCategories();
        if (count($children) > 0) {
            $success = true;
            foreach ($children as $child) {
                $success = $this->setAnchor($child);
            }
        } else {
            $success = true;
        }
        return $success;
    }

    protected function setAnchor($category) {
        $category->setIsAnchor(1);
        if (!$category->save()) {
            return false;
        }
        return true;
    }
}

You can assign the index controller action to a menu item and then on click, you're able to anchor all categories quickly.