Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress API: Add / Remove Tags on Posts

Tags:

php

wordpress

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;
}
like image 698
st4ck0v3rfl0w Avatar asked Mar 12 '10 23:03

st4ck0v3rfl0w


2 Answers

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;
}
like image 97
Byron Whitlock Avatar answered Oct 18 '22 12:10

Byron Whitlock


Try using wp_add_post_tags($post_id,$tags);

like image 21
streetparade Avatar answered Oct 18 '22 12:10

streetparade