This add-on for Broadcast cleans up unused media by searching through the database.
The best time to use this add-on is after making major changes to the media library. Perhaps after copying all media to a CDN and then modifying the posts to refer to the image in the CDN, instead of referring to the images using media IDs in the post.
The add-on is not foolproof and can, at best, present you with an educated guess of which media files are being used – so please backup your database and files before testing and especially before doing any changes to the live site.
There are currently two ways of detecting unused media: database and files.
The database search
This search is run solely on the database. It can search the custom fields (postmeta), options table and post content for occurrences of the media ID or media URL or both.
Searching custom fields (postmeta)
Custom fields can be searched for the media ID and / or URL.
When searching for the ID, the default is to search for:
- As the sole value of the postmeta: 123
- At the start of the postmeta: 123,
- In the middle of the postmeta: ,123,
- At the end of the postmeta: ,123
The defaults can be modified using actions by your developer. See the snippet heading below.
Searching for the URL will search for the media’s reported guid.
Searching the options table
This is similar to the postmeta search.
Per default the IDs and URL are searched for in the same way as above.
Searching the post content
The post content can also be searched similarly, except with a focus on shortcodes since shortcodes are usually in the format: [image id=”123″] or [image_gallery ids=”123,234,456″]
- The media ID as the whole shortcode attribute: =”123″
- The media ID at the start of a shortcode: =”123,
- The media ID at the end of a shortcode: ,123″
- The media ID in the middle of a shortcode: ,123,
- The URL appearing anywhere in the post content.
There are two media delete types:
- Allowing WordPress itself to delete the media from the library and from disk, wp_delete_post. This is the default and should work for most people.
- Only deleting the media from library using database SQL commands. This leaves the media on disk.
Use the SQL delete when you have media items that, somehow, share the same media file on disk. If you don’t have duplicates, you’ll be fine with the wp_delete_post method.
The file search
This search is run on disk and compared to the database. It searches for files on disk that are not registered in the database and offers the option to delete them from disk.
In the case of images, the search will only show the full sized image. When deleting the resized versions are automatically deleted also.
Snippets
See this snippet it you wish to modify the regexps used during the database search.
This snippet will remove all non-images from the search results.