Set tags for a post – without tag creation

OK, so you have something like this:

$new_tags = array( 'tag1', 'tag2', 'tag3' );
wp_set_post_tags( $post_ID, $new_tags );

If you want to add only tags that already exist, then you have to filter your tags array:

$new_tags = array( 'tag1', 'tag2', 'tag3' );
$existing_tags = array();
foreach ( $new_tags as $t ) {
    if ( term_exists( $t, 'post_tag' ) ) {
        $existing_tags[] = $t;
    }
}
wp_set_post_tags( $post_ID, $existing_tags );

Or a shorter version:

$new_tags = array( 'tag1', 'tag2', 'tag3' );
wp_set_post_tags( $post_ID, array_filter( $new_tags, 'tag_exists' ) );

Leave a Comment