Batch Exporting and Zipping User-Uploaded Photos in WordPress for Download

On some WordPress sites, users are allowed to upload photos (e.g., through a front-end form or a membership system). Over time, these photos can accumulate. If the site administrator needs to download all photos uploaded by a specific user or from a specific period for offline processing, manually downloading them one by one via FTP or the Media Library is very inefficient. This article introduces how to use PHP to batch export specified photos and compress them into a Zip file for easy download.

Core Logic for Batch Export

The core steps are: first, query the database for the file paths of the photos that meet the criteria; second, use PHP’s ZipArchive class to create a new Zip file and add these photos to it; finally, provide the path to the Zip file for the user to download.

function wprs_export_user_photos($user_id)
{
    // Get all attachments uploaded by the user
    $args = [
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'post_status'    => 'inherit',
        'posts_per_page' => -1,
        'author'         => $user_id,
    ];

    $query = new WP_Query($args);
    $files = [];

    if ($query->have_posts()) {
        foreach ($query->posts as $post) {
            $files[] = get_attached_file($post->ID);
        }
    }

    if (empty($files)) {
        return false;
    }

    // Create Zip file
    $zip      = new ZipArchive();
    $zip_name = 'user-' . $user_id . '-photos-' . time() . '.zip';
    $zip_path = WP_CONTENT_DIR . '/uploads/temp/' . $zip_name;

    if (!file_exists(dirname($zip_path))) {
        mkdir(dirname($zip_path), 0755, true);
    }

    if ($zip->open($zip_path, ZipArchive::CREATE) === true) {
        foreach ($files as $file) {
            if (file_exists($file)) {
                $zip->addFile($file, basename($file));
            }
        }
        $zip->close();

        return content_url('uploads/temp/' . $zip_name);
    }

    return false;
}

Security Considerations

When implementing such a feature, security is paramount:

  • Permission Check: Ensure only administrators or authorized users can trigger the export.
  • Temporary File Management: Zip files can be large. It’s best to set up a Cron job to regularly clean up the temp directory.
  • Timeout and Memory Limits: If there are thousands of photos, the script might time out or exceed the PHP memory limit. In such cases, consider processing in batches or using background tasks.

Conclusion

Using PHP’s built-in ZipArchive class combined with WordPress’s WP_Query, we can easily implement a batch export feature. This significantly improves the efficiency of managing user-uploaded content.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *