n Create menu link programmatically in drupal 8 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

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(){

    'title' => 'Contact US',
    'link' => ['uri' => 'internal:/node/2'],
    'menu_name' => 'main',
    'weight' => 10,

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,

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



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


Page Facebook