views:

371

answers:

3

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;
}
+2  A: 

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;
}
Byron Whitlock
FYI: is_term has been changed to term_exists
Brad
+1  A: 

Try using wp_add_post_tags($post_id,$tags);

streetparade
+1  A: 

Here is how I do it:

$tag="This is the tag"
$PostId=1; //
wp_set_object_terms( $PostId, array("$TAG"), 'post_tag', true );

*Note: wp_set_object_terms() expects the second parameter to be an array.*

Lars Koudal