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

Drupal 8 and Behat tests

Adding automated tests to small or create-and-forget projects probably doesn't make sense. You will spend additional time writing those tests, and this will only increase the project's cost. And you will get almost nothing in return. But, if you are working on a project that will be maintained in the future and new features will be added on a regular basis, then you most certainly need to add automated tests.

Drupal 8, nginx and Let's Encrypt

This site is powered by Drupal 8. I'm using nginx as a web server and Let's Encrypt to add HTTPS encryption to my site. In this post I will show you how my nginx config file looks like.