Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A function that hooks into WordPress and, when a $_GET request with a key of "download" and a value that contains a Base64 encoded array of semi-colon separated file URLS is passed, generates the ZIP on the fly and downloads it
add_action('wp', 'handle_all_file_downloads');
function handle_all_file_downloads() {
if (isset($_GET) && isset($_GET['download'])) {
$urls = base64_decode($_GET['download']);
if ($urls) {
$urls = (strpos($urls, ';') !== false) ? explode(';', $urls) : array($urls);
$path = wp_upload_dir();
$zip = new ZipArchive();
$zip_name = uniqid('dwwindsor-download-');
$zip_path = $path['basedir'] . '/' . $zip_name . '.zip';
if (file_exists($zip_path)) {
unlink($zip_path);
}
if ($zip->open($zip_path, ZIPARCHIVE::CREATE) === true) {
$zip->addEmptyDir($zip_name);
foreach ($urls as $url) {
$parameters = explode('/', $url);
$zip->addFromString($zip_name . '/' . end($parameters), file_get_contents($url));
}
$zip->close();
header('Content-disposition: attachment; filename=' . $zip_name . '.zip');
header('Content-type: application/zip');
@readfile($zip_path);
unlink($zip_path);
exit;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.