这周我遇到了你的情况,最后我使用树节点实现了解决方案。这是解决方案:
public function addItemsToTopmenuItems($observer)
{
/** @var Varien_Data_Tree_Node */
$menu = $observer->getMenu();
/** @var Varien_Data_Tree*/
$tree = $menu->getTree();
/** @var Varien_Data_Tree_Node_Collection */
$menuCollection = $menu->getChildren();
/** @var array of Varien_Data_Tree_Node*/
$nodes = $menuCollection->getNodes();
//Get "inlcude in navigation menu" parent CMS pages
$collection = Mage::getModel('cms/page')->getCollection()
->addFieldToFilter('include_in_nav',true)
->addFieldToFilter('is_active',true)
->addFieldToFilter('parent_id', array(array('null' => true), array('eq' => 0)))
->setOrder('sort_order');
$cmsHelper=Mage::helper('cms/page');
foreach ($collection as $item) {
$node = new Varien_Data_Tree_Node(array(
'name' => $item->getData('title'),
'id' => $item->getData('identifier'),
'url' => $cmsHelper->getPageUrl($item->getData('page_id')), // point somewhere
), 'id', $tree, $menu);
$menu->addChild($node);
$parent_id = $item->getData('page_id');
$this->getAllChilds($node,$parent_id);
}
}
还有getAllChilds函数:
private function getAllChilds($node,$parent, $defaultNode = null){
$cmsHelper=Mage::helper('cms/page');
$pages = Mage::getModel('cms/page')
->getCollection()
->addFieldToSelect('title')
->addFieldToSelect('page_id')
->addFieldToSelect('identifier')
->addFieldToFilter('parent_id', $parent)
->addFieldToFilter('is_active', 1)
->load();
$tree = $node->getTree();
if(count($pages) > 0) {
foreach ($pages as $item){
$data = array(
'name' => $item->getData('title'),
'id' => $item->getData('identifier'),
'url' => $cmsHelper->getPageUrl($item->getData('page_id')),
);
$subNode = new Varien_Data_Tree_Node($data, 'id', $tree, $node);
$node->addChild($subNode);
$node = $this->getAllChilds($subNode,$item->getData('page_id'), $node);
}
$node = $this->getAllChilds($subNode,$item->getData('page_id'));
}
$childNode = $node;
if($defaultNode !== null)
$childNode = $defaultNode;
return $childNode;
}
但是您需要在 cms 表中添加一些额外的数据,例如“parent_id”字段。这是我的 mysql4-install-0.1.0.php 文件:
<?php
$installer = $this;
$installer->startSetup();
$table = $installer->getTable('cms/page');
$installer->getConnection()->addColumn($table,'parent_id',array(
'type' =>Varien_Db_Ddl_Table::TYPE_INTEGER,
'comment' => 'Parent CMS Page'
));
$installer->getConnection()->addColumn($table,'include_in_nav',
array(
'type' =>Varien_Db_Ddl_Table::TYPE_BOOLEAN,
'comment' => 'Include in navigation menu'
));
$installer->getConnection()->addColumn($table,'position',
array(
'type' =>Varien_Db_Ddl_Table::TYPE_INTEGER,
'comment' => 'Position from navigation (category) menu. 1=left; 2=right'
)); //1: left; 2: right
$installer->endSetup();
最后,您需要将这些字段添加到 CMS / Pages 后端菜单:https://www.atwix.com/magento/adding-custom-attribute-to-a-cms-page/
最好的问候!