Programmatically create a menu link for a node

Creating a menu link programmatically in Drupal 8 and 9 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.

Image

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.

Image

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.