0

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.

3

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');
  • 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
0

@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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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