Dec 20, 2019 in Drupal 8, Snippets

When creating seed data, for example in your modules hook_install() script, creating a menulink can be necessary. This snippet shows how.

1) Menu link to a node

use Drupal\menu_link_content\Entity\MenuLinkContent;

$menu_link = MenuLinkContent::create(array(
 'title' => 'My page',
 'link' => ['uri' => 'entity:node/'.$node->id()], // The node you'd like to link to
 'menu_name' => 'custom-menu', // Your menu name
 'weight' => -20,
 'bundle' => 'menu_link_content',
));
$menu_link->save();

2) Menu link to a url/page

use Drupal\menu_link_content\Entity\MenuLinkContent;

$menu_link = MenuLinkContent::create(array(
 'title' => 'My page',
 'link' => ['uri' =>'internal:/my-page'], // The node you'd like to link to
 'menu_name' => 'custom-menu', // Your menu name
 'weight' => -20,
 'bundle' => 'menu_link_content',
));
$menu_link->save();