Programmatically add attributes to Menu Link Content

With Drupal, to add attributes to your menu links you would use Menu Link Attributes or Link Attributes widget which will provide UI to add additional attributes like class, ref, target, etc.

However, it might be unclear how to add those attributes if you create it programmatically.

See bellow a simple example.

use Drupal\menu_link_content\Entity\MenuLinkContent;

$menuLink = MenuLinkContent::create(
  [
    'title' => 'Best Content Management system and website builder',
    'provider' => 'my_provider',
    'menu_name' => 'main',
    'link' => [
      'uri' => "https://lunadxp.com/",
      'options' => [
        'attributes' => [
          'class' => 'special-class',
          'target' => '_blank',
        ],
      ],
    ],
  ]
)->save();

 

Retrieve attributes as following

/** @var \Drupal\Core\Menu\MenuLinkInterface $menuLink */
$attributes = $menuLink->getUrlObject()->getOption('attributes');
********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************

Sign up for my newsletter

I send out an email every so often about cool stuff I'm working on and things I've learned.

Thank you!