Created
November 17, 2020 03:27
-
-
Save MogulChris/34f4029a14050e1505df3856b6884a10 to your computer and use it in GitHub Desktop.
Clean up unused Wordpress 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 | |
//1. Get all attachment IDs | |
//2. Check if the ID appears as a simple meta value, or as a meta value like "[id]" (including quotes, to catch serialized values) or like wp-image-[id] (for wysiwyg ACF fields and such) | |
//3. Check if the ID appears in post_content like wp-image-[id] | |
//TODO - WordPress galleries. N/A in my case but probably needs its own check. | |
//If an ID does not appear in the above scenarios, get it gone. | |
require_once('wp-load.php'); | |
//switch_to_blog(10); //if on multisite, work on a specific blog | |
global $wpdb; | |
$rows = $wpdb->get_results('SELECT ID from ' . $wpdb->prefix . 'posts WHERE post_type = "attachment"'); | |
echo 'Total: ' . count($rows) . "\n"; | |
$not_found = []; | |
foreach($rows as $row){ | |
$id = $row->ID; | |
$found = false; | |
$content_like = '%wp-image-' . $id . '%'; | |
$sql = 'SELECT post_id FROM ' . $wpdb->prefix . 'postmeta WHERE meta_value = ' . $id . ' OR meta_value LIKE "%\"' . $id . '\"%" OR meta_value LIKE "' . $content_like . '"'; | |
//echo $sql . "\n"; | |
$featured = $wpdb->get_results( $sql ); | |
if(!empty($featured)) $found = true; | |
if(!$found){ //try to match in post content | |
$post_content = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'posts WHERE post_content LIKE "' . $content_like .'"'); | |
if(!empty($post_content)) $found = true; | |
} | |
echo "$id " . ($found ? 'found' : 'not found') . "\n"; | |
if(!$found) $not_found[] = $id; | |
} | |
echo 'Found ' . count($not_found) . ' possibly unused attachments'; | |
//optionally output to a file rather than immediately delete | |
//file_put_contents('not_found.json', json_encode($not_found)); | |
foreach($not_found as $id){ | |
echo get_the_title($id). "\n"; | |
wp_delete_attachment($id,true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also need to look for image URLs in case they are embedded that way