Drupal - PHP Add Taxonomy Term

Q: How can I programmatically create or add new Taxonomy Terms using PHP code?
A: 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! ;-)

Stranger
Stranger's picture
I thought that perhaps

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

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can use BBCode tags in the text.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Pride on FacebookPride on TwitterPride on TwitterPride on Twitter

Join Our Newsletter

* indicates required

Irish Internet Association

finalist.png
phone-number.png