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.

Programmatically create a menu link for a node
Programmatically create a menu link for 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.

Programmatically create a menu link for a node
Programmatically create a menu link for a node

About the author

Goran Nikolovski is a highly experienced Drupal developer with an extensive skill set that includes PHP, MySQL, HTML, CSS and Javascript. He has experience with large Drupal sites and Drupal Commerce 2.x integration, and he is author of several Drupal modules.