WordPress: forzare il download di un file allegato

WordPress: forzare il download di un file allegato

In WordPress è possibile forzare il download di un file allegato.

Avendo ottenuto l'ID del file, possiamo implementare la seguente soluzione.


function my_file_download() {
	if( isset( $_GET['file'] ) && is_numeric( $_GET['file']) ) {
		$file = get_attached_file( intval( $_GET['file'] ) );

		if ( file_exists( $file ) ) {
			header( 'Content-Description: File Transfer' );
			header( 'Content-Type: application/octet-stream' );
			header( 'Content-Disposition: attachment; filename="'.basename( $file ).'"' );
			header( 'Expires: 0' );
			header( 'Cache-Control: must-revalidate' );
			header( 'Pragma: public' );
			header( 'Content-Length: ' . filesize( $file ) );
			readfile( $file );
			exit;
		}
	}
}

Torna su