Magento 2 / WordPress Integration Menus

First Published: March 25, 2015

WordPress provides an easy to use UI to create and manage menus. This data can be easily accessed in Magento code.

The below code example shows how to load a WordPress menu by it's ID or by a menu location. It then shows how to output the menu. This can be done as an array, which can be used for debugging the menu or outputting in your own custom format. You can also use the NavMenu block and this generates the HTML structure of the menu for you.

// First we get the MenuRepository to load our menu
$menuRepository = $objectManager->create(
   \FishPig\WordPress\Model\MenuRepository::class
);

// Next we can load the menu. We can do this by menu ID or menu location
// Here we load by ID. Change 1234 to the ID of your menu
$menu = $menuRepository->get(1234);

// Or we can load by menu location
$menu = $menuRepository->getByLocation('primary_menu');

// Now that we have our $menu object, we need to output it in some way

// First lets debug it as an array
var_dump($menu->getMenuTreeArray());

// Now lets output it as HTML. First get the Layout object.
// If in a PHTML file, you can just do $block->getLayout(). If in a PHP file
// you should use DI to inject the Layout object
$layout = $objectManager->get(
    \Magento\Framework\View\Layout::class
);

// Now get the NavMenu block
$navMenuBlock = $layout->createBlock(
    \FishPig\WordPress\Block\Sidebar\Widget\NavMenu::class
);

// We can load the nav menu using a already loaded $menu object
$navMenuBlock->setMenu($menu);

// Or we can load it using a menu ID
$navMenuBlock->setNavMenu(1234);

// Now lets output the content of the menu
echo $navMenuBlock->toHtml();