Skip to content

Instantly share code, notes, and snippets.

@JustAdam
Created August 2, 2012 09:49
Show Gist options
  • Save JustAdam/3235992 to your computer and use it in GitHub Desktop.
Save JustAdam/3235992 to your computer and use it in GitHub Desktop.
Drupal 7 - Programmatically create a taxonomy and attach a field to it, then create a content type and attach that taxonomy to it.
<?php
// Machine name for our custom node
define('NODE_NAME', 'the_node_machine_name');
// Machine name for our custom taxonomy
define('TAXONOMY_NAME', 'the_taxonomy_machine_name');
function module_install() {
_create_taxonomy();
_create_content_type();
}
/**
* Create a taxonomy and attach a field to it.
*/
function _create_taxonomy() {
$t = get_t();
$term = new stdClass();
$term->name = $t('Name');
$term->machine_name = TAXONOMY_NAME;
$term->description = $t('Description');
$term->heirarchy = 1;
$term->module = 'module_name';
$term->weight = 1;
taxonomy_vocabulary_save($term);
// Create a field
$field = array(
'field_name' => 'field_tax_fieldname',
'type' => 'text',
'label' => $t('Label')
);
field_create_field($field);
// Attach the field to our taxonomy entity
$instance = array(
'field_name' => 'field_tax_fieldname',
'entity_type' => 'taxonomy_term',
'bundle' => TAXONOMY_NAME,
'label' => $t('Label'),
'description' => $t('Description'),
'required' => true,
'widget' => array(
'type' => 'text_textfield',
'weight' => 3
)
);
field_create_instance($instance);
// Done
}
/**
* Create a content type and attach our created taxonomy to it.
*/
function _create_content_type() {
$t = get_t();
$node = array(
'type' => NODE_NAME,
'name' => $t('Name'),
'base' => 'node_content',
'description' => $t('Description'),
'title_label' => $t('Title'),
'custom' => TRUE
);
$content_type = node_type_set_defaults($node);
node_add_body_field($content_type, $t('Article'));
node_type_save($content_type);
// Create a taxonomy field and use the taxonomy entity we created earlier
$field = array(
'field_name' => 'field_tax_name',
'type' => 'taxonomy_term_reference',
'label' => $t('Label'),
'settings' => array(
'allowed_values' => array(
array(
'vocabulary' => TAXONOMY_NAME,
'parent' => 0
)
)
)
);
field_create_field($field);
// Add the field to the content type as a HTML select box.
$instance = array(
'field_name' => 'field_tax_name',
'entity_type' => 'node',
'bundle' => NODE_NAME,
'label' => $t('Label'),
'description' => '',
'required' => TRUE,
'widget' => array(
'type' => 'options_select',
'weight' => -10,
)
);
field_create_instance($instance);
// Done
}
@SkurkovPO
Copy link

Thank you very much

@Melonangie
Copy link

Thank You!!!

@Xosmond
Copy link

Xosmond commented Jul 21, 2016

Any example to add a text field or a list field? Please

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment