Roots Discourse

No more attachment pages or author pages

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;
        }
    }
} );

Gist

2 Likes

Nice! This looks like a simple version of this post: https://gschoppe.com/wordpress/disable-attachment-pages/, though the author page redirect is a great little addition.

I’ve got a PR open in @withjacoby’s soberwp/intervention project that implements the approach that I linked to, if anyone’s in need of a slightly different approach to the attachment page problem.

Thanks for sharing!