I can use wp_set_post_tags to set tags for a post. According to documentation,

Every tag that does not already exist will be automatically created

I don’t want to automatically create tag if tag does not exit?

So is there any function can I use?

1
1

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

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *