Programmatically create a menu link for a node

Programmatically create a menu link for a node

Creating a menu link programatically in Drupal 8 is easy. You have to provide four values, link title and uri, menu name for which you want to create a menu link, and optionally you can provide a link weight. Take a look at the following code:

use Drupal\menu_link_content\Entity\MenuLinkContent;

MenuLinkContent::create([
  'title' => 'Menu title',
  'link' => ['uri' => 'internal:/node/1'],
  'menu_name' => 'main',
  'weight' => -45,
])->save();

But when you create a menu link like this, you won't see a menu link in the "Menu settings" section of a node.

All you have to do for this to work is to change internal to entity, like this:

use Drupal\menu_link_content\Entity\MenuLinkContent;

MenuLinkContent::create([
  'title' => 'Menu title',
  'link' => ['uri' => 'entity:node/1'],
  'menu_name' => 'main',
  'weight' => 0,
])->save();

and now you will see that "Provide a menu link" checkbox is checked and you will also see other menu link options.

You may also like

An alternative to Menu Token module

As of writing this blog post, Menu Token module for Drupal 8 is still in the alpha version and it might not work in all cases. That's why having an alternative solution is great. The alternative to using Menu Token module for Drupal 8 is to use Menu link plugins.