6

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?

8

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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