Skip to main content
Category:

Code snippet that can be used to create menu link programmatically in drupal 8.

to add menu links juste use MenuLinkContent::create() function where you want.

Here an example with custom menu link:

use Drupal\menu_link_content\Entity\MenuLinkContent;

/**
 * hook_cron()
 */
function mymodule_cron(){

  MenuLinkContent::create([
    'title' => 'Contact US',
    'link' => ['uri' => 'internal:/node/2'],
    'menu_name' => 'main',
    'weight' => 10,
  ])->save();
}

Here an example with submenu creation:

juste add 'parent' option.

'parent' => 'route.name',

Or you can use this example:

$menu_link_content = MenuLinkContent::create([
  'title' => 'Menu',
  'link' => ['uri' => 'internal:/node/2'],
  'menu_name' => 'main',
  'weight' => 2,
  'expanded' => TRUE,
]);
$menu_link_content->save();

$mid = $menu_link_content->getPluginId();
$menu_link_2 = MenuLinkContent::create([
  'title' => 'Submenu',
  'link' => ['uri' => 'internal:/node/3'],
  'menu_name' => 'main',
  'weight' => 21,
  'parent' => $mid,
]);
$menu_link_2->save();

 

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook