To load a menu item from a given node we need to use the plugin.manager.menu.link service, which has a method called loadLinksByRoute().
/** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menuLinkManager */
$menuLinkManager = \Drupal::service('plugin.manager.menu.link');
$result = $menuLinkManager->loadLinksByRoute('entity.node.canonical', ['node' => $node->id()], 'main');
/** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $menuItem */
$menuItem = array_pop($result);If the node has menu items then the $result variable will now contain an array of MenuLinkContent objects. Using array_pop() will get you the first item in the list.
Add new comment