Many of you have noticed that if you create a link to a file, this file will open in a new browser window. To download, users have to right click and select save link as. This may be too many steps for some. The sample below uses an MP3 as an example.

First set up your link and send the file path to it on with a variable.

The way I do this is with a Custom field “mymp3_value” in the post level which I pass with a link

[php]
<a href="<?php bloginfo(‘url’); ?>/filedownload.php?download=<?php echo get_post_meta($post->ID, ‘mymp3_value’, true) ?>">DOWNLOAD MP3</a>
[/php]

Save the next code as filedownload.php and place it in your root folder
[php]
<?php
$name_of_file = $_GET["download"];

header(‘Content-Description: File Transfer’);
// We’ll be outputting a MP3
header(‘Content-type: application/mp3′);
// It will be called file.mp3
header(‘Content-Disposition: attachment; filename=’ .$name_of_file);
header(‘Content-Length: ‘.filesize($name_of_file));
header(‘Content-Transfer-Encoding: binary’);
header(‘Expires: 0′);
header(‘Cache-Control: must-revalidate, post-check=0, pre-check=0′);
header(‘Pragma: public’);
// The MP3 source is in somefile.pdf
//readfile("somefile.mp3");

readfile_chunked($name_of_file);

function readfile_chunked($filename){
$chunksize = 1*(1024*1024); // how many bytes per chunk
$buffer = ”;
$handle = fopen($filename, ‘rb’);
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
print $buffer;
}
return fclose($handle);
}
?>
[/php]

If you a bit of knowledge of php you can easily adapt this code to create different file types and pass this information with the link as well.
You can create an download link for your files easily.

This post was written by

Frederick Pohl – who has written posts on Hire WordPress Developer | WordPress Theme Developer | WordPress Experts Developers - Wp1stop.
Frederick Pohl is a WordPress Developer and 2001 University of Florida Graduate in Electronic Intermedia. He has been specializing in Web Development and Graphic Design since 1997. He has spent the last 7 years focusing in providing WordPress custom services to a Worldwide clientele based out of Gainesville, FL. We provide complex customizations and theme design. I work 1on1 with all my clients and offer a top quality service. Request a Free quote and Hire us for your WordPress project.

Email  • Google +

Leave a Reply

You must be logged in to post a comment.