WordPress – remove unattached files from upload folder

1 month, 3 weeks ago 0
Posted in: Programování
function clean_uploads_from_nonattachments(){
	$uploads_dir = wp_upload_dir(); 
	$search = $uploads_dir['basedir'];
	$replace = $uploads_dir['baseurl'];

	$uploads_dir = ( $uploads_dir['basedir']); 
	$root = $uploads_dir;

	$iter = new RecursiveIteratorIterator(
		new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
		RecursiveIteratorIterator::SELF_FIRST,
		RecursiveIteratorIterator::CATCH_GET_CHILD 
	);
	foreach ($iter as $fileinfo) {
		if ($fileinfo->isFile()) {	
			$image = $fileinfo->getPathname();
			$image_url = str_replace($search, $replace, $image);
			$attachment_id = attachment_url_to_postid($image_url);
				//Not found - then delete file 
				if (!$attachment_id){
					unlink($image);	
				}
				else {
					echo $attachment_id.': '.$image; 			   
				}	
		}
	}			
}

Comments are closed.