Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Is there a php function which can add/remove tags of posts? If not how would I do this?

I am looking for something like this:

add_tag($post_id, 'tag-name');
remove_tag($post_id, 'tag-name');
share|improve this question

1 Answer 1

up vote 5 down vote accepted

The key function you're looking for here is wp_set_post_tags().

To add the tag 'awesome' to post 98,

wp_set_post_tags( 98, array( 'awesome' ), true );

Note that the true parameter means that this tag will be added to the existing post tags. If you omit this value, it defaults to false, and the existing post tags will be overwritten with the new ones being passed.

To delete a tag, first pull up a list of the existing post tags using https://codex.wordpress.org/Function_Reference/wp_get_post_tags:

$tags = wp_get_post_tags( 98 );

Then assemble a list of the tags you want to keep (which will exclude the one you're "deleting"), and replace the existing post tags with the new list:

$tags_to_delete = array( 'radical', 'bodacious' );
$tags_to_keep = array();
foreach ( $tags as $t ) {
    if ( !in_array( $t->name, $tags_to_delete ) ) {
        $tags_to_keep[] = $t->name;
    }
}

wp_set_post_tags( 98, $tags_to_keep, false );
share|improve this answer
    
wow... i have looked for this for a long while... didnt knew about wp_ wp_set_post_tags - the only missing part in a front end article edit form :) - thanks a bunch –  Sagive SEO Jul 16 '12 at 14:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.