WordPress 101 Guide | Make a File Download Link Part #1

//WordPress 101 Guide | Make a File Download Link Part #1

WordPress 101 Guide | Make a File Download Link Part #1

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.

By | 2012-04-03T11:19:30+00:00 April 3rd, 2012|Categories: Wordpress 101 Guide|0 Comments

About the Author:

Leave A Comment