3

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.

1 Answer 1

11

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);
2
  • 1
    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, 2018 at 21:01
  • Thanks this worked great. Just a note that I added this to get to the actual MenuLinkContent object /* @var $menuLink Drupal\menu_link_content\Plugin\Menu\MenuLinkContent */ $menuLink = array_pop($result); which gives you an instance of api.drupal.org/api/drupal/… Oct 5, 2020 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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