DEV Community

Cover image for Code to auto-download files from WordPress?
tacqiya
tacqiya

Posted on

Code to auto-download files from WordPress?

Image description

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');
Enter fullscreen mode Exit fullscreen mode

We are checking here whether the file exists or not,

if (file_exists($file_path))
Enter fullscreen mode Exit fullscreen mode

On the else part used for getting the file path

echo WP_CONTENT_DIR.parse_url($file, PHP_URL_PATH);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)