Force Attachment Pages to Download File
Intercepts attachment page requests and serves the attached file as a forced browser download instead of displaying the page.
PHPby SnipCraft
php
<?php
if ( ! function_exists( 'scseed_force_attachment_download' ) ) {
function scseed_force_attachment_download() {
if ( ! is_attachment() ) {
return;
}
$post = get_post();
$file_path = get_attached_file( $post->ID );
if ( ! $file_path || ! file_exists( $file_path ) ) {
return;
}
$mime_type = get_post_mime_type( $post->ID );
$filename = basename( $file_path );
header( 'Content-Description: File Transfer' );
header( 'Content-Type: ' . $mime_type );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
header( 'Content-Length: ' . filesize( $file_path ) );
header( 'Cache-Control: must-revalidate' );
readfile( $file_path );
exit;
}
add_action( 'template_redirect', 'scseed_force_attachment_download' );
}#attachments#download#files#media