Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

2 Answers 2

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
2  
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

 
discard

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.