Hey teams,
I often write some variation of this for clients who want simpler websites, and while it’s nothing fancy (at all), it’s nice to have it on the tool belt. This snippet added to filters.php or wherever will cause template lookups for author or attachment pages to redirect the request to the parent post or home page. Also if anyone sees anything dangerous in this, I’d love to get feedback.
Always check that the core functions used are still recommended when copying snippets.
/**
* Redirect away from attachment and author pages
*
*/
add_action('template_redirect', function() {
if (is_attachment() || is_author()) {
global $post;
if ($post && $post->post_parent) {
wp_redirect(esc_url(get_permalink($post->post_parent)), 301);
return;
} else {
wp_redirect(esc_url(home_url('/')), 301);
return;
}
}
} );