Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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".

Comments

Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

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

Web Posts

Search

Page Facebook