Your function replaces EVERY tag_name occurence in the content. Meaning, it will replace <h2>my-tag</h2>
into <h2><a href="https://wordpress.stackexchange.com/questions/307147/tag-link">my-tag</a></h2>
.
I’m assuming you add the tag names to the content manually. Then i would add them with an identifier. For example add the tags to your content like this:
This is my content, i can add tags that transform into links like
this: {tag_name}
Then change your function into:
/**
* Scan post content and replace {tag_name} with tag link
**/
add_filter( 'the_content', 'post_content_change_my_tags_into_links' );
function post_content_change_my_tags_into_links( $content ) {
$tags = get_terms( 'post_tag' );
if ( $tags ) {
foreach ( $tags as $tag ) {
$change="{".$tag->name.'}';
$into = sprintf( '<a href="https://wordpress.stackexchange.com/questions/307147/%s">%s</a>', esc_url( get_term_link( $tag ) ), esc_html( $tag->name ) );
$content = str_replace($change, $into , $content);
}
}
return $content;
}
NOTE 1: ONLY tags that have posts connected will transform into links.
NOTE 2: be carefull with short function names like link_words()
if the function is in the global namespace (directly in functions.php). Duplicate function names will result in an error 500.