Last active
August 21, 2019 11:15
-
-
Save tangrufus/3e7a4fa4cba1d981e1e7a72d93151aac to your computer and use it in GitHub Desktop.
Find corrupted wordpress image attachments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: