wp-sweep-uploads (ok)

wp eval-file wp-sweep-uploads.php
<?php
/**
 * @author  Filipe Seabra
 * @link    https://wp-cli.org/
 * @version 1.0.0
 *
 * Put this file in the root directory of your WordPress installation.
 *
 * You make better usage of this file by using WP CLI (link above). Command line example:
 * `wp eval-file wp-sweep-uploads.php`.
 */

/**
 * In case you are not using WP CLI to execute this file uncomment the line below.
 * NOT RECOMMENDED.
 */
//require_once 'wp-load.php'; // Assumes this file is located within WordPress root installation folder.

// Keeps the full path to your WordPress installation uploads folder.
$uploads_dir = wp_get_upload_dir()['basedir'];

// Keeps all occurrences found within the uploads/ folder.
$years = array_filter(
	array_diff(
		scandir( $uploads_dir ),
		/**
		 * Add to this list any other directory/file name you want to exclude from the scan.
		 */
		array(
			'.',
			'..',
			'index.php',
			'wc-logs',
			'woocommerce_uploads',
		)
	),
	function ( $v ) use ( $uploads_dir ) {
		if ( ! is_dir( $uploads_dir . "/$v" ) ) {
			return false;
		}

		return true;
	}
);

foreach ( $years as $year ) {
	// Keeps all occurrences found within the uploads/{year}/ folder.
	$months = array_filter(
		array_diff(
			scandir( $uploads_dir . "/$year" ),
			/**
			 * Add to this list any other directory/file name you want to exclude from the scan.
			 */
			array(
				'.',
				'..',
				'index.php',
			)
		),
		function ( $v ) use ( $uploads_dir, $year ) {
			if ( ! is_dir( $uploads_dir . "/$year/$v" ) ) {
				return false;
			}

			return true;
		}
	);

	foreach ( $months as $month ) {
		// Keeps all occurrences found within the uploads/{year}/{month}/ folder.
		$images = array_filter(
			array_diff(
				scandir( $uploads_dir . "/$year/$month" ),
				/**
				 * Add to this list any other directory/file name you want to exclude from the scan.
				 */
				array(
					'.',
					'..',
					'index.php',
				)
			),
			function ( $v ) use ( $uploads_dir, $year, $month ) {
				if ( is_dir( $uploads_dir . "/$year/$month/$v" ) ) {
					return false;
				}

				return true;
			}
		);

		/**
		 * Notice that in order to use $wpdb you have to load WordPress core.
		 *
		 * @global $wpdb
		 */
		global $wpdb;

		foreach ( $images as $image ) {
			$query = "SELECT post_id, meta_key, meta_value FROM ";
			$query .= $wpdb->prefix . "postmeta WHERE meta_key = '_wp_attachment_metadata' ";
			$query .= "AND meta_value LIKE '%$image%' LIMIT 1";

			$r = $wpdb->get_results( $query );

			if ( empty( $r[0] ) ) {
				// DELETES THE IMAGE FILE THAT IS NOT BEING USED BY THE WORDPRESS MEDIA LIBRARY!
				unlink( $uploads_dir . "/$year/$month/$image" );
			}
		}
	}
}

Last updated