在WordPress中的ZIP下载多个图像



我在分发图像的个人WordPress网站上工作。

在单个帖子页面中,我通过ACF注册了几张图像(高级自定义字段),我知道如何通过get_field ACF函数获取图像路径/文件名。

我只是谷歌搜索然后找到了此页面,但是如何将此技术应用于WordPress网站?将多个图像下载到zip

现在我被卡住了...

在单个帖子页面上,放置download_zip.php文件的URL,您将在其中放置所有代码以创建zip。

在单个帖子页面上:

<a href="<?php echo site_url().'/download_zip.php?model_id='.$post->ID; ?>">Download ZIP</a>

在变量'model_id'中,将单个帖子的帖子ID放置。

现在在WordPress设置的根上创建一个download_zip.php文件,其中存在wp-config.php文件。

这是download_zip.php文件的代码。

<?php 
/*File for downloading the gallery zip files*/
$post_id = $_GET['model_id'];
require_once('wp-blog-header.php');
require_once('/wp-admin/includes/file.php');
WP_Filesystem();
$files_to_zip = array();
$zip = new ZipArchive();
$title = get_the_title($post_id); 
$destination = wp_upload_dir(); 
//var_dump($destination); 
$destination_path = $destination['basedir'];
$DelFilePath = str_replace(" ","_",$title).'_'.$post_id.'_'.time().'.zip' ;
$zip_destination_path = $destination_path."/".$DelFilePath;
if(file_exists($destination_path."/".$DelFilePath)) {
    unlink ($destination_path."/".$DelFilePath); 
}
 if ($zip->open($destination_path."/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
        die ("Could not open archive");
}
//this is only for retrieving Repeater Image custom field
$row1 = get_field('acf_field_name1',$post_id);
$row1 = get_field('acf_field_name2',$post_id);
$rows = array($row1,$row2);
if($rows) {
foreach($rows as $row): ?>
    <?php  
    $explode = end(explode("uploads",$row));
    $index_file = array($destination_path,$explode);
    $index_file = implode("",$index_file);
    $new_index_file = basename($index_file);
    $zip->addFile($index_file,$new_index_file);
endforeach; 
}
$zip->close();
if(file_exists($zip_destination_path)) {
    send_download($zip_destination_path);
}
//The function with example headers
function send_download($file) {
    $basename = basename($file);
    $length   = sprintf("%u",filesize($file));
    header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
    header('Content-Description: File Transfer');
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="'.$basename.'"');
    header('Content-Transfer-Encoding: binary');
    header('Pragma: public');
    header('Content-Length: ' . $length);
    set_time_limit(0);
    ob_clean();
    flush();
    readfile($file); // "Outputs" the file.
    unlink($file);
}
?>

请根据您的要求修改此代码,例如get_field(),将image field name放入其中,&amp;定义您的上传目录,以便您可以在$explode变量中打破url,以在$index_file变量中定义图像路径。

,请检查您存储在$destination_path变量中的destination path是否正确。

希望,这可能对您有帮助。

最新更新