Try this, which should work, and if necessary, replace the artist
on the 5th line below with the correct taxonomy slug:
add_action( 'template_redirect', 'my_301_redirect_tag_to_artist' );
function my_301_redirect_tag_to_artist() {
if ( is_tag() ) {
// Check if an "artist" term exists with the same slug as the current tag.
$artist = term_exists( get_queried_object()->slug, 'artist' );
if ( is_array( $artist ) && isset( $artist['term_id'] ) ) {
$artist_id = (int) $artist['term_id']; // this ensures it's an integer
// Perform a safe 301 redirect to the "artist"/term archive page.
wp_safe_redirect( get_term_link( $artist_id ), 301 );
exit;
}
}
}
Things to note:
-
is_tag()
is one of the many conditional tags in WordPress, andis_tag()
checks if the current page is a tag archive, where “tag” here refers to the corepost_tag
taxonomy in WordPress. You can learn more about conditional tags here. -
term_exists()
checks if a specific term (tag, category or custom taxonomy’s term) exists in the WordPress database, and basically returns an array containing the term ID if the term does exist. -
get_queried_object()
retrieves the data of the current term where the slug normally presents in the current URL as inhttps://example.com/tag/tag-slug/
.Or without permalinks or URL rewriting, the above URL might look like
https://example.com/?tag=tag-slug
instead. -
wp_safe_redirect()
, as the name implies, safely redirects to a local URL, i.e. a location at your WordPress website. And in my example, you could see that I explicitly set the status (the 2nd parameter) to 301 because the default one is 302. -
get_term_link()
retrieves the permalink/URL of a term, and in your case, the URL would look likehttps://example.com/artist/artist-slug/
. -
template_redirect
is an action hook which fires before WordPress determines and loads the template for the current request, and I used it because the documentation stated:This action hook executes just before WordPress determines which
template page to load. It is a good hook to use if you need to do a
redirect with full knowledge of the content that has been queried.The last 10 words in the last sentence means, by the time the hook runs, WordPress has already setup the main query and determined what the request is for (e.g. a Page, a term archive, a search results page, etc.), and thus conditional tags would work as expected.
So I hope that helps, and be sure to visit the above links and understand those functions, instead of simply copy-pasting my code. 🙂 Happy coding!