Drupal - PHP Add Taxonomy Term

Kevin's picture

[b]Q:[/b] How can I programmatically create or add new Taxonomy Terms using PHP code?
[b]A:[/b] Call the function taxonomy_save_term() passing in the details of the new taxonomy term.

To create a new taxonomy term through PHP you can use taxonomy_save_term(&$form_values) which is mainly intended for use as a helper function to by the real drupal taxonomy add term form. The relevant term details are passed in via the $form_values parameter and the Term Id of the newly created taxonomy term is placed back in this array and can be accessed by the calling code. I wrote the following function wrap taxonomy_save_term(&$form_values) to make it a bit easier to use:


function add_taxonomy_term($name, $vid, $description = '', $weight = 0) {

$form_values = array();
$form_values['name'] = $name;
$form_values['description'] = $description;
$form_values['vid'] = $vid;
$form_values['weight'] = $weight;
taxonomy_save_term($form_values);

return $form_values['tid'];
}

It is passed the name of the new term, the Id of the vocabulary under which it is to be created and optionally a description and a weight. The Id of the new term is returned.

I thought that perhaps somebody might find this code useful, and ill find it here if ever I need it again! ;-)

Share this post: 

Recent Work

Some of Ireland's biggest brands use Pride Design to Design, Build, Manage, Market and Maintain their websites.

Website design for St.Patricks Credit Union in Dublin, Including Loan Calculators.

Website design and development for a step by step wedding and other stationary ordering website f

New website designed and developed for Cork's newest café, which is based in Merchants Quay in Co

New Website design for Pain Relief clinic based in Cork City.

Website for a busy Dublin city centre pub.

We redrafted the Ballymaloe house website to modernise the look and feel of the site and to also

We revamped the website for the Ballymaloe Cookery School.

We revamped the Cully & Sully website onto Drupal.

Rachel Allen was brought up in Dublin and left home at eighteen to study at the world-famous Ball

Clóna Dairy Products are a Dairy Company based in Clonakilty, Co. Cork, since 1919.

Project Arts Centre is Ireland’s leading centre for the presentation and development of c