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.
Add a comment
|
1 Answer
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);
-
1Which 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.– leymannxCommented 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/… Commented Oct 5, 2020 at 16:31