Lets break this apart using your question title:
Get the tags as an array, convert the tag into a string, and then replace spaces with dash
Get the tags as an array
get_the_tags
is the correct function, you now have one of 2 things:
- an array of term objects ( a tag is a term in the tags taxonomy )
false
, there are no tags on this post- A
WP_Error
object, something went wrong
So we need to check for those cases, afterall if we assume tags are returned but there are none, what will happen? We have to tell it what will happen or undefined things will happen, and that could be anything, probably a 500 error
So lets update the first bit of code:
$tags = get_the_tags();
if ( is_wp_error( $tags ) ) {
return; // there was an error
}
if ( false === $tags ) {
return; // there were no tags on this post
}
// now we can do stuff with the tags
Convert The Tag into a string
Nifty, now we have an array of tags. You mentioned there should only be 1 tag, but who knows what plugins might be adding their own tags, so lets make sure your code handles that correctly:
foreach ( $tags as $tag ) {
// do something with our tag
break; // exit after the first one
}
Replace the spaces with dashes
Each $tag
is a WP_Term
object, you can use the terms slug with $tag->name
, which will already have the URL friendly version
However, why bother? There’s a function for that! We can replace this:
echo 'Post by: <a href="https://wordpress.stackexchange.com/meet-the-team/employees/". $newname ."https://wordpress.stackexchange.com/">'. $newname .'</a>';
With:
$url = get_term_link( $tag, 'tags' );
echo 'Post by: <a href="'.esc_url( $url ).'">'.esc_html( $tag->name ).'</a>';
Notice I added escaping. Escaping is important and will prevent most hacks. Despite it’s anti-hacking superpowers, it’s almost never applied to WordPress code 🙁