Because of server issues & browser blocking auto-download, here’s rather an effective method for auto-downloading any file in WordPress.
Create a function in functions.php of your theme folder.
function file_download()
{
if (isset($_GET['file'])) {
$file = base64_decode($_GET['file']);
$file_name = basename($file); //sanitize_file_name($file);
$file_path = $_SERVER['DOCUMENT_ROOT'] . parse_url($file, PHP_URL_PATH);
if (file_exists($file_path)) {
header("Content-Disposition: attachment; filename=$file_name");
readfile($file_path);
exit;
} else {
echo WP_CONTENT_DIR . parse_url($file, PHP_URL_PATH);
}
}
}
add_action('init', 'file_download');
We are checking here whether the file exists or not,
if (file_exists($file_path))
On the else part used for getting the file path
echo WP_CONTENT_DIR.parse_url($file, PHP_URL_PATH);
You can use “File not found” for showing an error display.
Here we’re passing a get method here to get the dynamic file the user wants to download.
https://example-wp.com/?file=file-url

Top comments (0)