I know I can use the UI at admin/config/people/accounts/fields to add existing taxonomy fields.

But I want to create them automatically using my module.

I know I can use hook_enable() or hook_install() for this but I don't know which hook or function I need to use to make the field show up in admin/config/people/accounts/fields ( and on the user edit / registration page )

I've read somewhere something about a bundle but I'm not sure if I'm looking in the right direction there.


You need to create an instance of the field, and then attach it to your content type. This is done using the field_create_instance() function.

There's a nice example in the standard profile of attaching the 'Tags' vocabulary to the article content type upon install:

$instance = array(
  'field_name' => 'field_' . $vocabulary->machine_name,
  'entity_type' => 'node',
  'label' => 'Tags',
  'bundle' => 'article',
  'description' => $vocabulary->help,
  'widget' => array(
    'type' => 'taxonomy_autocomplete',
    'weight' => -4,
  'display' => array(
    'default' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    'teaser' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,

The documentation page has a full list of all the available properties for your field instance, but the above code is an excellent place to start.

I also have this piece of code in my arsenal which dumps the field/instance definitions of an existing field so I can inspect it and just chop and change what I need to:

$entity_type = 'node';
$field_name = 'field_FIELDNAME';
$bundle_name = 'BUNDLE_NAME';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');
|improve this answer|||||
  • so in this case ( adding it to a user ) the bundle_name should be users ? – FLY May 29 '12 at 8:22
  • 1
    It's just user (without the s). The bundle's defined in user_entity_info() in case you're interested – Clive May 29 '12 at 8:25
  • turns out that my vocabulary machine name wasn't the same as the field_name causing errors and not creating the instance. thanks for showing this answer so I could check that it wasn't the code that was wrong :) – FLY May 29 '12 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.