Skip to content

Instantly share code, notes, and snippets.

@alanef
Created April 16, 2018 19:59
Show Gist options
  • Select an option

  • Save alanef/217e72618395060a8ecbd7da1ec1f034 to your computer and use it in GitHub Desktop.

Select an option

Save alanef/217e72618395060a8ecbd7da1ec1f034 to your computer and use it in GitHub Desktop.
Remove unused images
<?php
/* create this code in a file in the main wordpress directory e.g. delmedia.php
and access it via mydomain.com/delmedia.php
obviously this can do serious damage
set to delete 100 a time to avoid time outs and menatto be run perioidically by cron
otherise run directly by php command line and don't worry about limits
*/
// Include the wp-load'er
include('wp-load.php');
// build an array of images here by scanning options and post meta for any image files names
$safe = array();
$args= array(
'post_type' => 'attachment', // obvious
'posts_per_page' => -1 // get them all
);
// get all attachments post ids
echo "start<br>";
$posts = get_posts( $args );
echo "got<br>";
$i=0;
echo count($posts)."<br>";
foreach ($posts as $post_id) {
// get an array of image data
$image_attributes = wp_get_attachment_image_src( $post_id->ID );
if ($post_id->post_parent==0) {
if (!empty($image_attributes[0])) {
$i++;
if ($i>100) {
break;
}
if (// some sort or array search of $safe and $image_attributes[0] to check if not to be kept //) {
echo '<br>Image Found : '.$i." - ".$image_attributes[0];
if (false === wp_delete_attachment( $post_id->ID, true ) ) {
echo ' and delete failed!<br>';
} else {
echo ' and delete succeeded!<br>';
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment