Skip to main content
Category:

Code snippet that can be used to permanently delete unused/orphaned files in drupal 8.

/**
 * override hook_cron()
 */
function mymodule_cron()
{
  // get all files ids
  $fids = Drupal::entityQuery('file')->execute();
  $file_usage = Drupal::service('file.usage');
  // loop all fids and load files by fid
  foreach ($fids as $fid) {
    $file = Drupal\file\Entity\File::load($fid);
    $usage = $file_usage->listUsage($file);
    // check if file not used
    if (count($usage) == 0) {
      $file->delete();
    }
  }
}

to excute this code just run your cron and check your files at "/admin/content/files".

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook