Removing sanitize_title_with_dashes Function with The Real Title

wp_add_post_tags($thePostID, $target); assumes that $target is either the slug or ID of a tag. Not all possible values will be valid tag slugs, which is why the sanitize_title_with_dashes is used.

So instead, the real problem is that those tags have no human friendly name, just a slug.

So instead, fetch the term, use it’s ID, and if it doesn’t already exist, create it and use the new term ID

Fetch the term:

$name = str_replace("'","''",str_replace(";","",$query));
$slug = sanitize_title_with_dashes($name);
$term = get_term_by( 'slug', $slug, 'tag' );

If it wasn’t found:

if ( false === $term ) {

Then create the tag:

    $term = wp_insert_term( $name, 'tag', [
        'slug' => $slug
    ]);

Finally, add it to your post:

}
wp_set_object_terms( $post_id, $term, 'tag', true );

Notice that I cut out the middle man by eliminating all the tag helper functions, and going straight for the term and taxonomy functions. Why learn a whole new set of functions for tags, then again for taxonomy, each behaving slightly differently, when you can learn 1 set of functions that work the same for everything

Performance and Functionality

This entire approach is bad for performance, scaling, and database load, because it makes changes on the frontend. This makes your entire site much slower.

Additionally, it makes page caching impossible, any page cache that gets added to this, or query caching, will cause this functionality to either fail or become very unreliable.

Instead, have you considered using Google Analytics or Jetpack stats which automatically track this information already?