0

Create a JS and get the PDF links from Hidden Field

jQuery(document).ready(function($){
    $('.download_all').on('click', function(e){
        e.preventDefault();
                 var pdfUrls = $('#all_pdf').val();
        if(pdfUrls == 'undefined') {
            alert('Please select at least one PDF.');
            return;
        }
        $.ajax({
            url: ajaxurl, 
            type: 'POST',
            data: {
                action: 'download_pdfs_zip',
                pdf_urls: pdfUrls
            },
            xhrFields: {
                responseType: 'blob'
            },
            success: function(response) {
                const blob = new Blob([response], { type: 'application/zip' });
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = 'documents.zip';
                link.click();
            },
            error: function(xhr, status, error) {
                console.error(error);
                alert('Failed to download ZIP file.');
            }
        });
    });
});

Next create a AJAX to get the ZIP

//ZIP REPORT PDF
add_action('wp_ajax_download_pdfs_zip', 'handle_download_pdfs_zip');
function handle_download_pdfs_zip() {
    $pdf_urls = isset($_POST['pdf_urls']) ? explode(',', $_POST['pdf_urls']) : [];
    if (empty($pdf_urls) || !is_array($pdf_urls)) {
        wp_send_json_error('No PDF URLs provided');
    }
    $zip = new ZipArchive();
    $zip_filename = tempnam(sys_get_temp_dir(), 'pdfs') . '.zip';
    if ($zip->open($zip_filename, ZipArchive::CREATE) !== TRUE) {
        wp_send_json_error('Could not create ZIP file');
    }
    foreach ($pdf_urls as $url) {
        $file_content = file_get_contents($url);
        if ($file_content !== false) {
            $path_parts = pathinfo($url);
            $filename = sanitize_file_name($path_parts['basename']);
            $zip->addFromString($filename, $file_content);
        }
    }
    $zip->close();
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="documents.zip"');
    header('Content-Length: ' . filesize($zip_filename));
    readfile($zip_filename);
    unlink($zip_filename);
    exit;
}

Jagdish Sarma Asked question May 16, 2025
Add a Comment