Taxonomies are very useful in Drupal when you need to organize your content but sometimes the default and available fields are not enough. Here is an example how you can add some to you taxonomy vocabulary.
If you want to create a taxonomy from a PHP script, here is what you could do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$obj->name = $t("My Custom Vocabulary Name"); $obj->machine_name = "my_custom_vocabulary_name"; $obj->hierarchy = 2; $obj->module = "taxonomy"; taxonomy_vocabulary_save($obj); // http://api.drupal.org/api/function/field_create_field/7 foreach ($array_fields as $field) { field_create_field($field); } // Create all the instances for our fields. // http://api.drupal.org/api/function/field_create_instance/7 foreach ($array_instances as $instance) { field_create_instance($instance); } |
Some fields examples ($array_fields)
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 30 31 32 33 34 35 |
$array_fields = array( 'tax_critere_id' => array( 'field_name' => 'tax_critere_id', 'type' => 'text', 'module' => 'text', 'active' => '1', 'cardinality' => '1', ), 'tax_critere_type' => array( 'field_name' => 'tax_critere_type', 'cardinality' => 1, 'foreign keys' => array( 'tid' => array( 'columns' => array( 'tid' => 'tid', ), 'table' => 'taxonomy_term_data', ), ), 'indexes' => array( 'tid' => array( 0 => 'tid', ), ), 'settings' => array( 'allowed_values' => array( 0 => array( 'vocabulary' => 'my_other_vocabulary_types', 'parent' => '0', ), ), ), 'type' => 'taxonomy_term_reference', ), ); |
Some instances examples ($array_instances)
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 30 31 32 |
$t = get_t(); $array_instances = array( 'tax_critere_id' => array( 'label' => $t('Id Critere'), 'field_name' => 'tax_critere_id', 'widget' => array( 'type' => 'text_textfield', ), 'entity_type' => 'taxonomy_term', 'bundle' => 'my_custom_vocabulary_name', ), 'tax_critere_type' => array( 'field_name' => 'tax_critere_type', 'label' => $t('Type'), 'widget' => array( 'active' => 1, 'module' => 'options', 'settings' => array(), 'type' => 'options_select', ), 'display' => array( 'default' => array( 'label' => 'above', 'module' => 'taxonomy', 'settings' => array(), 'type' => 'taxonomy_term_reference_link', ), ), 'entity_type' => 'taxonomy_term', 'bundle' => 'my_custom_vocabulary_name', ), ); |
To load the taxonomy vocabulary when it is created:
1 2 3 4 |
$termvocab = taxonomy_vocabulary_machine_name_load("my_custom_vocabulary_name"); if (is_object($termvocab)) { // Do you work here } |
Hi,
This code add field’s to vocabulary itself or it’s terms?
both !
Thanks this works :)
At first it has error because of typo
foreach ($array_fields
)
as $field) {field_create_field($field);
}
just remove the
)
it and it will work fine.. thanks again :)Nice. I didn’t find the typo in my code though
Hi !
Typo error : first block > line 8.
Thanks for your help :)
Thanks :)
Thank you so much , you saved my time