Skip to content

Instantly share code, notes, and snippets.

@Langmans
Last active July 9, 2018 20:41
Show Gist options
  • Save Langmans/b7115b3b3f6847283f364a063035198a to your computer and use it in GitHub Desktop.
Save Langmans/b7115b3b3f6847283f364a063035198a to your computer and use it in GitHub Desktop.
<?php
// removes orphaned images
// as in no attachment record.
require __DIR__ . '/wp-load.php';
ob_implicit_flush( true );
set_time_limit( 0 );
/** @var \wpdb */
global $wpdb;
$files = glob( 'wp-content/uploads/*/*/*' );
if ( $files ) {
foreach ( $files as $file ) {
if ( is_dir( $file ) ) {
continue;
}
$post_name = $wpdb->esc_like( preg_replace( '@-\d+x\d+[^.]*\.@', '.', $file ) );
$res = $wpdb->get_results( $q = "select * from $wpdb->posts where (post_name like '%$post_name' or guid like '%$post_name') AND post_type = 'attachment'" );
if ( ! $res ) {
echo 'Unlinking ', $file, '<br>', PHP_EOL;
unlink( $file );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment