How to programmatically create menu items when creating nodes?

I create some nodes programmatically, this way:

foreach ($titles as $t) { $n = new stdClass(); $n->type = 'myType'; $n->uid = 1; $n->title = $t; $menu = array(); $menu['link_title'] = $t; $menu['menu_name'] = 'primary-links'; // this attempt at placing the menu item in a particular place in the // menu hierarchy didn't work: $menu['parent'] = 'primary-links:867'; $menu['depth'] = 3; $menu['p1'] = '580'; $menu['p2'] = '867'; $n->menu = $menu; node_save($n); } 

I have a menu structure like this:

 primary-links Parent 1 Child 1 Child 2 Parent 2 Child 3 

I want the new menu items to appear as child elements of Child 3. I managed to create the menu items at the same time as the nodes, and they appeared in the right menu, but not in the right place in the hierarchy. What am I missing?

+4
source share
3 answers

I think you complicate this too much. Previously, when I programmatically created menu items for nodes, I simply set the folder_name, link_title and plid (parent link identifier), that is:

 $menu['link_title'] = $t; $menu['menu_name'] = 'primary-links'; $menu['plid'] = 867; 

The menu module takes over at some point during the node_save call and does the rest for you.

~ Matt

+4
source

In drupal 7 you also need to set the value to 1 (see menu_node_save () ):

 $node->menu = array( 'link_title' => $node->title, 'menu_name' => 'main-menu', 'plid' => 0, 'enabled' => 1, ); 
+6
source

Also needed to add

'description' => ''

to an array, otherwise I got an error for Drupal 7

+2
source

Source: https://habr.com/ru/post/1306406/


All Articles