29

How to Disable the Attachment Page in WordPress

Powered by WPCodeBox

WordPress Is Creating Attachment Pages You Don’t Need, you can Stop That with Code


function redirect_attachments() {
    if (!is_attachment()) {
        return;
    }

    $attachment = get_post();
    $parent_id = $attachment->post_parent;
    $parent_post_status = get_post_status($parent_id);
    $parent_permalink = get_permalink($parent_id);

    $destination = home_url();
    $http_status_code = 302;

    if($parent_id && $parent_post_status !== 'trash') {
        $destination = $parent_permalink;
        $http_status_code = 301;
    }

    wp_safe_redirect($destination,$http_status_code);

    exit;

}

add_action('template_redirect', 'redirect_attachments', 1);
We also have a video in which we use this snippet:

Other Snippets

WPCodeBox is a WordPress Code Snippets Manager that allows you to share your WordPress Code Snippets across your sites.