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' => '',

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,




Add new comment

Restricted HTML


Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.


Contact Us

All the content is FREE but I still need your help


Become a patreon