Skip to content

Instantly share code, notes, and snippets.

@tangrufus
Last active August 21, 2019 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangrufus/3e7a4fa4cba1d981e1e7a72d93151aac to your computer and use it in GitHub Desktop.
Save tangrufus/3e7a4fa4cba1d981e1e7a72d93151aac to your computer and use it in GitHub Desktop.
Find corrupted wordpress image attachments
<?php
$mineTypes = get_allowed_mime_types();
$imageMineTypes = array_filter($mineTypes, function (string $type): bool {
return '' !== 'image/' && 0 === strpos($type, 'image/');
});
$query = new WP_Query([
'fields' => 'ids',
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => $imageMineTypes,
'posts_per_page' => -1,
]);
$imageIds = $query->get_posts();
// Create csv file if not exists.
$csvFilename = 'corrupted-wordpress-image-attachments.csv';
exec("touch $csvFilename");
$csvPath = realpath($csvFilename);
WP_CLI::log("Exporting to $csvPath");
$fp = fopen($csvPath, 'wb');
// CSV header.
fputcsv($fp, [
'id',
'title',
'url',
'edit',
'path',
]);
foreach ($imageIds as $id) {
// Find local image path (non-offloaded).
$path = get_attached_file($id, true);
if (! file_exists($path)) {
continue;
}
$output = null;
$statusCode = null;
// Requires ImageMagick.
// See: https://stackoverflow.com/a/46805566
exec("identify -regard-warnings -verbose ${path} > /dev/null 2>&1", $output, $statusCode);
if (0 === $statusCode) {
continue;
}
$title = get_the_title($id);
// Find non-offloaded image URL.
$url = str_replace(WP_CONTENT_DIR, WP_CONTENT_URL, $path);
$edit = admin_url("post.php?post=$id&action=edit");
fputcsv($fp, [
$id,
$title,
$url,
$edit,
$path,
]);
}
fclose($fp);
WP_CLI::success('Done!');
@tangrufus
Copy link
Author

tangrufus commented Aug 21, 2019

$ wp eval-file find-corrupted-wordpress-image-attachments.php

Note:

  • This bypass WP Offload Media
  • Requires ImageMagick

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment