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

How to create menu link programmatically in drupal 8 & 9


If you would like to create module-defined menu links, add something like this example to your file:

  title: 'Example Link'
  description: 'Description link'
  route_name: example.route_name
  weight: 10
  enabled: 0
  route_parameters: { key: 'value' }
  menu_name: account 
      uid: 1
      target: _blank
        - btn
        - btn-primary


  title: "Contact"
  description: "Scroll to contact section"
  url: "internal:#contact"


Example 2:

In order to create a menu item automatically this can be placed in a hook_update_N on the file MODULENAME.install and will run when the database is updated (/update.php):

use Drupal\menu_link_content\Entity\MenuLinkContent;

$items = array(
  '1' => 'Menuitem 1',
  '2' => 'Menuitem 2',
  '3' => 'Menuitem 3'

foreach($items as $nid => $title) {
  $menu_link = MenuLinkContent::create([
    'title' => $title,
    'link' => ['uri' => 'internal:/node/' . $nid],
    'menu_name' => 'main',
    'expanded' => TRUE,


You can also create an entire Menu programmatically:

    'id' => 'menu_test',
    'label' => 'Test menu',
    'description' => 'Description text',


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