Drupal 8: Remove all medias entities from the site programmatically

23 Aug.2019
drupal entities

Sometimes we need to completely remove media entities, for example, when you copy a site for another project.

You can use custom code in your custom module or install devel_php and run with admin interface on /devel/php.

Below are two examples.

$ids = \Drupal::entityQuery('media')->execute();
$storageHandler = \Drupal::entityTypeManager()->getStorage('media');
$entities = $storageHandler->loadMultiple($ids);
$storageHandler->delete($entities);

For small and middle websites.

$ids = \Drupal::entityQuery('media')->execute();
$storageHandler = \Drupal::entityTypeManager()->getStorage('media');
$entities = $storageHandler->loadMultiple($ids);
foreach ($entities as $entity) {
  $entity->delete();
}

For large websites, when you have, for example, 20k+ entities.

$ids = \Drupal::entityQuery('media')->condition('bundle', 'image_event')->execute();
$storageHandler = \Drupal::entityTypeManager()->getStorage('media');
$entities = $storageHandler->loadMultiple($ids);
foreach ($entities as $entity) {
  $entity->delete();
}

Works in case if you want to load all media by bundle/type and delete after.

$ids = \Drupal::entityQuery('media')->execute();
$storageHandler = \Drupal::entityTypeManager()->getStorage('media');
$entities = $storageHandler->loadMultiple($ids);
foreach ($entities as $entity) {
  // Remove media created by an anonymous user only.
  if ($entity->getOwnerId() == 0) {
     $entity->delete();
  }
}

Remove media created by an anonymous user only.