Skip to content

Instantly share code, notes, and snippets.

@BhargavBhandari90
Created September 18, 2025 13:42
Show Gist options
  • Save BhargavBhandari90/11097adce2f2324cad55fef4fc527714 to your computer and use it in GitHub Desktop.
Save BhargavBhandari90/11097adce2f2324cad55fef4fc527714 to your computer and use it in GitHub Desktop.
<?php
// Get non-optimised image list in batch with generator
function fp_scan_all_images()
{
$upload_dir = wp_upload_dir();
$uploads_path = $upload_dir['basedir'];
$uploads_url = $upload_dir['baseurl'];
$optimized_path = WP_CONTENT_DIR . '/flying-press-images';
$batch = [];
$batch_count = 100;
foreach (fp_scan_images_generator() as $file) {
$optimized_file = str_replace($uploads_path, $optimized_path, $file);
if (is_file($optimized_file)) {
continue;
}
$batch[] = $file;
if (count($batch) >= $batch_count) {
error_log(print_r($batch,true));
$batch = [];
}
}
if ($batch) {
error_log(print_r($batch,true));
}
}
function fp_scan_images_generator()
{
try {
$upload_dir = wp_upload_dir();
$directory = $upload_dir['basedir'];
// Recursive scan with FileSystemIterator
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS)
);
if (empty($iterator)) {
return [];
}
foreach ($iterator as $file) {
if (
!$file->isFile() ||
!in_array(strtolower($file->getExtension()), ['jpg', 'jpeg', 'png'], true)
) {
continue;
}
yield $file->getPathname();
}
} catch (\Throwable $e) {
error_log('FlyingPress: Error scaning images - ' . $e->getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment