Try this:
function custom_set_term_to_post(){
$args = array(
'post_type' => 'post',
);
$all_posts = get_posts();
foreach ($all_posts as $key => $post) {
$tag_name="post_tag"; // required tag name
$term_list = wp_get_post_terms($post->ID, $tag_name, array("fields" => "ids"));
if (!empty($term_list)) {
// there is already tags; need not do anything
continue;
}
$tag = array( 23 ); // required tag ID to assign
wp_set_post_terms( $post->ID, $tag, $tag_name );
}
}
This function scans all posts of post type post
and check if it has any tag or not. If no any tag is assigned, then required tag is assigned. Here tag name is post_tag
. And required tag item is of id 23
. Replace it with your value.
Make sure this function only run once. Just for current purpose. Dont leave it in the theme. 🙂