Creating a menu link programmatically

A friend of mine asked how to create a link programmatically in Drupal. I do this sort of stuff all the time, because one of the projects I help with requires us to write update scripts for our deployments. Let me outline two ways to do this, one via the Forms API, and the other using menu_link_save.

Forms API

In Drupal, you can build a form array containing the values which would be submitted in a form, and then pass them to a function to simulate actually submitting the form. In Drupal 6, you use drupal_execute, which was renamed to drupal_form_submit in Drupal 7. It looks like this (in Drupal 6):

$form_state = array();
$form_state['values']['menu'] = array(
  'link_path' => 'some-drupal-path',
  'link_title' => 'Link Title',
  'description' => '',
  'enabled' => 1,
  'expanded' => 0,
  'parent' => 'primary-links:0',
  'weight' => 0,
  'customized' => 1,
drupal_execute('menu_edit_item', $form_state, 'add', NULL, array('menu_name' => 'primary-links'));

In Drupal 7, simply replace the drupal_execute function above with drupal_form_submit.

drupal_form_submit('user_register_form', $form_state);


However, I'm not a big fan of the phpvious method, because it usually complicates things unnecessarily. I recommend doing using menu_link_save, which is the same in Drupal 6 and Drupal 7.

$item = array(
  'link_path' => 'some-drupal-path',
  'link_title' => 'Link Title',
  'menu_name' => 'primary-links',