I have seen the post on how to create menu items programmatically in Drupal 8, but how do I update or delete menu items in D8?

Clarification: by programmatically I mean dynamically so yaml config files are not going to help.


First you will have to load the entity. Either way works:

$menu_link = MenuLinkContent::load($menu_link_id);

or ...

$menu_link = \Drupal::entityTypeManager()->getStorage('menu_link_content')->load($menu_link_id);

Next you can update value using set() method or through the magic method __set...

$menu_link->expanded = TRUE;

To save, simply call the save() method. To delete, simply call the delete() method.

  • 1
    You are using a mlid there, might seem like I am appending an additional question but where would you get that from, ie. how do you traverse a menu's tree? – Duncanmoo May 4 '17 at 12:20
  • In which hook we need to do all these? I am creating a theme and I override menu--main.html.twig file to style the menu. This code has to go in .theme file? in which hook? – siddiq Dec 11 '17 at 1:37

I had to do some thing like ....

 //menuLinkManager = 'plugin.manager.menu.link'
$result = $this->menuLinkManager->loadLinksByRoute('entity.node.canonical', ['node' => $node->id()]);
foreach ($result as $menu_item) {
          if (is_object($menu_item)) {
            $id = $menu_item->getPluginDefinition()['metadata']['entity_id'];
$menu_link = $this->entityTypeManager->getStorage('menu_link_content')->load($id);
$menu_link->enabled = 0;


Probably too late I did like:

$menu_handler = \Drupal::service('menu.link_tree')
    ->load("menu-name", new \Drupal\Core\Menu\MenuTreeParameters());
foreach($menu_handler as $key=>$value) {
  if('Name' == $value->link->getTitle()) {
    $link = $value->link;
        'title'=>'New Name'

This is how i delete all the links in a particular menu like footer

$old_menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['menu_name' => 'footer']);
foreach ($old_menu_links as $old_menu_link) {

And to update existing menu,

$menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['menu_name' => 'footer']);
foreach ($menu_links as $menu_link) {

  if ($menu_link->gettitle() == 'old-title') {
    $menu_link->set('title', 'new-title');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.