how to programmatically change post tags

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');

1 Answer
1

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 );

Leave a Comment