Your asking for command line solution, I don’t have one – but for PHP you can cycle through all posts, build an array of files, compare it to an array of the media library, find unused and delete.
Cycle through Posts
use get_posts()
for pages
andor posts
, and build your foreach loop
Extract Media From Posts
while in the loop find the media items and build a big array of used media urls
function myplugin_find_media($content) {
$mediaRegex = "/(src|href)=\"(.+?).(jpg|png|pdf|gif)\"/i"; // your support filetypes
$mediaFind = preg_match_all($mediaRegex, $content, $media);
if (isset($media[2]) && count($media[2]) > 0)
return $media[2];
return false;
}
Get Library Items
You can get all library items with somthing like
// get the media library for comparison
$library = array();
$args = array(
'post_type' => 'attachment',
//'post_mime_type' => 'image', // if theres only one
'numberposts' => -1,
'post_status' => null,
'post_parent' => null,
);
$attachments = get_posts($args);
foreach ($attachments as $post)
$library[$post->ID] = wp_get_attachment_url($post->ID); // or add more info about thumbnails, etc
Compare library and Used Media Items
You can then loop through your library and compare it to your extracted used media items.
Note you’ll need to factor in the use of thumbnails and resized -###-###
images.
Deleting
With a library media item not being in any posts, and you’ve got it’s post ID as the key in $library
, you can use wp_delete_post()
to remove it completely.
Cleaning
If this site has a ton of extra thumbnails from different plugins and themes that have created their own sizes, a plugin like this can clean it for you.
UPDATE:
Looks like there’s a plugin that does this already: https://wordpress.org/plugins/media-cleaner/