Wordpress API: Add / Remove Tags on Posts
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 = intv开发者_如何学Cal($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)
;
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.
Since WordPress 3.6 there is wp_remove_object_terms( $object_id, $terms, $taxonomy )
that does exactly that.
The $terms
parameter represents the slug(s)
or ID(s)
of the term(s)
to remove and accepts array, int or string.
Source: http://codex.wordpress.org/Function_Reference/wp_remove_object_terms
What if you dont know the post id? You just want to add the tag to all new posts created?
When using the WordPress API function add_action('publish_post', 'your_wp_function');
, the function you are calling automatically gets the post_id
injected as the first argument:
function your_wp_function($postid) {
}
Actually, wp_set_object_terms can handle everything you need by itself:
If you really need a separate function:
function addTag($post_id, $term, $tax='post_tag') {
return wp_set_object_terms($post_id, $term, $tax, TRUE);
}
wp_set_object_terms
's parameters:
- the Post ID
- Accepts...
- a single string (e.g. 'Awesome Posts')
- a single ID of an existing tag (e.g. 1), or
- an array of either (e.g. array('Awesome Posts',1)).
- NOTE: If you provide a NON-ID, it will create the tag automatically.
- The taxonomy (e.g. for default tags, use 'post_tag').
- Whether to...
- (
FALSE
) REPLACE ALL existing terms with the ones provided, or - (
TRUE_
) APPEND/ADD to the existing terms.
- (
Happy coding!
精彩评论