I know it seems like a simple operation, but I can't find any resource or documentation that explains how to programmatically add and remove tags to a post using the post ID.
Below is a sample of what I'm using, but it seems to overwrite all the other tags...
function addTerm($id, $tax, $term) {
$term_id = is_term($term);
$term_id = intval($term_id);
if (!$term_id) {
$term_id = wp_insert_term($term, $tax);
$term_id = $term_id['term_id'];
$term_id = intval($term_id);
}
$result = wp_set_object_terms($id, array($term_id), $tax, FALSE);
return $result;
}
You need to first call get_object_terms to get all the terms that exist already.
Updated code
function addTerm($id, $tax, $term) {
$term_id = is_term($term);
$term_id = intval($term_id);
if (!$term_id) {
$term_id = wp_insert_term($term, $tax);
$term_id = $term_id['term_id'];
$term_id = intval($term_id);
}
// get the list of terms already on this object:
$terms = wp_get_object_terms($id, $tax)
$terms[] = $term_id;
$result = wp_set_object_terms($id, $terms, $tax, FALSE);
return $result;
}
Try using wp_add_post_tags($post_id,$tags)
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With