Skip to content

Instantly share code, notes, and snippets.

@aliboy08
Created February 1, 2024 07:20
Show Gist options
  • Save aliboy08/1c4344aa4f0597719980d4abb74ee3be to your computer and use it in GitHub Desktop.
Save aliboy08/1c4344aa4f0597719980d4abb74ee3be to your computer and use it in GitHub Desktop.
Wordpress dead images cleanup
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $id,
) );
$images = [];
foreach( $attachments as $attachment ) {
$images[] = $attachment->guid;
}
$dir = '/nas/content/live/harcourtscalou/wp-content/uploads/2023/11';
$scan = scandir($dir);
foreach( $scan as $item ) {
if( strpos($item, '__') === false ) continue;
$temp = explode('__', $item);
$base_name = $temp[0];
if( item_found( $base_name, $images ) ) {
continue;
}
$delete_file = $dir . '/'. $item;
unlink($delete_file);
}
function item_found( $item, $arr ) {
foreach( $arr as $arr_item ) {
if( strpos($arr_item, $item) !== false ) return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment