WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following code

$genres= array('action', 'comedy', 'horror');
foreach($genres as $genre){
      $ret = wp_set_object_terms( $postId, $genre, 'genres');

But this code associates only horror as the genre. When I checked the DB too, I don't have a record for action and comedy. How do I associate all the three with my genre?

Thanks in advance.

share|improve this question
up vote 3 down vote accepted

You can pass an array of terms to wp_set_object_terms, there is no need for the for each:

$genres= array('action', 'comedy', 'horror');
$ret = wp_set_object_terms( $postId, $genres, 'genres');
share|improve this answer
Alternately, pass true as the fourth argument to wp_set_object_terms so that the term you pass is appended to, rather than overwriting, the existing terms. – goldenapples Aug 23 '11 at 17:41
Thanks. It worked. – Albin Joseph Aug 24 '11 at 15:20

@Bainternet's answer got me on the right track, for storing a comma separated string of tags as individual tags in the database and associate each individual tag with the proper post.

I needed this, because I have a form field which allows users to enter a list of comma separated tags.

Anyway, here's the complete code I use:

// Sanitize user/form input
$custom_tags = trim(htmlspecialchars($_POST['custom_tags']));
// Explode returns the comma separated terms as an array
$custom_tags_separated = explode(',', $custom_tags);
// Pass the array of terms to wp_set_object_terms
wp_set_object_terms($post_id, $custom_tags_separated, 'custom_tag');
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.