I have a node (in D8) which is placed in the menu "Main navigation". How do I get the menu item (in code)? In Drupal 7 you could use $node->menu but in 8.x, the object is not populated with menu information. So, how do I retrieve it? I also want to support another type of menus in the future, so something which works with more than the menu_link_content module is appreciated.

up vote 7 down vote accepted

You can try this code:

use Drupal\menu_link_content\Entity\MenuLinkContent;

$node_id = 1;
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

dpm($result);
  • Which will give us an array of all menu items this node belongs to. We can then foreach for the menu name to get the one we need. – leymannx Apr 20 at 21:01

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.