Programmatically adding a node reference field to a type in Drupal 7

It wasn’t obvious how I could add new node reference fields to a content type. I had to work it out from node_reference_field_info() and from examining existing fields with field_info_field(). After some experimentation, this worked:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
$field = array(
    "field_name"=>;"field_field_name",
    "label"=>"Field label",
    "type"=>"node_reference",
    "settings"=>array(
      "referenceable_types"=>array(
        "gallery_image"=>"gallery_image"
      ),
    ),
    "cardinality"=>"-1"
  );
  field_create_field($field);
  $instance = array(
    "field_name"=>"field_field_name",
    "label"=>"Field label",
    "type"=>"node_reference",
    "widget"=>array(
      "type"=>"options_select"
    ),
  );
  $instance["entity_type"] = "node";
  foreach(array("type1", "type2", "type3") as $type){
    $instance["bundle"] = $type
    field_create_instance($instance);
  }

“gallery_image” is the machine name of the type that will be referenced by the field – put as many in here as you need (yes, the format really is “machine_name”=>”machine_name”). “cardinality” is the number of references in the field, -1 being unlimited. In the example, the field will be added to 3 types – type1, type2 and type3.