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;
}
Try using
wp_add_post_tags($post_id,$tags)
;Actually, wp_set_object_terms can handle everything you need by itself:
If you really need a separate function:
wp_set_object_terms
's parameters:FALSE
) REPLACE ALL existing terms with the ones provided, orTRUE_
) APPEND/ADD to the existing terms.Happy coding!
You need to first call get_object_terms to get all the terms that exist already.
Updated code
Since WordPress 3.6 there is
wp_remove_object_terms( $object_id, $terms, $taxonomy )
that does exactly that.The
$terms
parameter represents theslug(s)
orID(s)
of theterm(s)
to remove and accepts array, int or string.Source: http://codex.wordpress.org/Function_Reference/wp_remove_object_terms
When using the WordPress API function
add_action('publish_post', 'your_wp_function');
, the function you are calling automatically gets thepost_id
injected as the first argument:Here is how I do it:
Note:
wp_set_object_terms()
expects the second parameter to be an array.