Programmatically save taxonomy terms

You can programmatically save a taxonomy term using taxonomy_term_save(). To save multiple terms, create an array of terms and loop through them running taxonomy_term_save() for each iteration.

Why would you want to programmatically save taxonomy terms?

It is good practice to do code based development and automate changes in a deployment module. This saves you from repeatedly adding taxonomy terms on site, which saves time and reduces the chance of human error.

In the following code snippet, change term1 and term2 to your actual terms. Also change $term->vid to the ID of the vocabulary you are saving the terms to.

  $terms = array(
    'term1',
    'term2',
  );
  foreach ($terms as $name) {
    $term = new stdClass();
    $term->name = $name;
    $term->vid = 6;
    taxonomy_term_save($term);
  }

Comments

Perfect ! i use this code on compare-devis.fr and i found lots of code for insert nesw termes in new nodes and this is the snippet that works ! thanx !! Camille from France

Add new comment

Plain text

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.