Skip to content

Instantly share code, notes, and snippets.

@elenakondrateva
Created June 29, 2017 23:39
Show Gist options
  • Save elenakondrateva/8f5f646176b02dac2966b862e9a6510d to your computer and use it in GitHub Desktop.
Save elenakondrateva/8f5f646176b02dac2966b862e9a6510d to your computer and use it in GitHub Desktop.
Move Magento2 top menu categories under second level
<?php
namespace Acme\Topmenu\Plugin\Theme\Block\Html;
use Magento\Framework\Data\Tree\NodeFactory;
use Magento\Framework\Data\TreeFactory;
use Magento\Framework\Data\Tree\Node;
use Magento\Framework\Data\Tree;
class Topmenu
{
/**
* @var NodeFactory
*/
protected $nodeFactory;
/**
* @var TreeFactory
*/
protected $treeFactory;
/**
* Topmenu constructor.
* @param NodeFactory $nodeFactory
* @param TreeFactory $treeFactory
*/
public function __construct(
NodeFactory $nodeFactory,
TreeFactory $treeFactory
) {
$this->nodeFactory = $nodeFactory;
$this->treeFactory = $treeFactory;
}
public function beforeGetHtml(
\Magento\Theme\Block\Html\Topmenu $subject,
$outermostClass = '',
$childrenWrapClass = '',
$limit = 0
) {
/** @var Node $menu */
$menu = $subject->getMenu();
/** @var Tree $menuTree */
$menuTree = $menu->getTree();
/*** move categories under second level ***/
$categoriesNode = $this->getCategoriesNode($menuTree);
$menuNodesCollection = $menu->getChildren();
/** @var Node $categoryMenuItemNode */
foreach ($menuNodesCollection as $categoryMenuItemNode) {
$categoriesNode->addChild(clone $categoryMenuItemNode);
$menuNodesCollection->delete($categoryMenuItemNode);
}
$menu->addChild($categoriesNode);
}
/**
* @param Tree $tree
* @return Node
*/
private function getCategoriesNode(Tree $tree)
{
return $this->nodeFactory->create(
[
'data' => [
'name' => __('Category'),
'id' => 'categories',
'url' => '/categories/',
'has_active' => false,
'is_active' => false // (expression to determine if menu item is selected or not)
],
'idField' => 'id',
'tree' => $tree
]
);
}
}
@elenakondrateva
Copy link
Author

app/code/Acme/Topmenu/etc/module.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Acme_Topmenu" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Theme"/>
        </sequence>
    </module>
</config>

@elenakondrateva
Copy link
Author

app/code/Acme/Topmenu/registration.php:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Acme_Topmenu',
    __DIR__
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment