how to programmatically create menu items while cr

2019-05-06 15:04发布

I'm creating some nodes programmatically, thus:

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've got 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 children of Child 3. I was able to create menu items at the same time as the nodes, and they appeared in the correct menu, but not in the correct place in the hierarchy. What am I missing?

标签: api drupal
3条回答
Explosion°爆炸
2楼-- · 2019-05-06 15:13

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

$node->menu = array(
  'link_title' => $node->title,
  'menu_name' => 'main-menu',
  'plid' => 0,
  'enabled' => 1,
);
查看更多
ゆ 、 Hurt°
3楼-- · 2019-05-06 15:18

I think your over complicating it. In the past when I've programmatically created menu items for nodes, I just set the menu_name, link_title, and plid (parent link id), ie:

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

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

~Matt

查看更多
疯言疯语
4楼-- · 2019-05-06 15:25

Also had to add

'description' => ''

to the array otherwise I got an error for Drupal 7

查看更多
登录 后发表回答