Updating all Drupal media thumbnails

Jonathan Shaw
1 min readJul 15, 2020

--

I needed to update all the media thumbnails on my Drupal site, as they’d got confused somewhere along the way migrating from contrib media_entity to core media.

Using the batch updater function I wrote about previously this is pretty simple:

/**
* Updates all media thumbnails.
*
* Implement hook_deploy_NAME().
*/
function my_module_deploy_0001_update_thumbnails_after_migration_to_core_media(&$sandbox) {

$jobsLoader = function() {
return \Drupal::entityTypeManager()->getStorage('media')
->getQuery()
->accessCheck(FALSE)
->execute();
};

$jobProcessor = function($id) {
try {
$storage = \Drupal::entityTypeManager()->getStorage('media');
$media = $storage->load($id);
foreach ($media->getTranslationLanguages() as $langcode => $data) {
if ($media->hasTranslation($langcode)) {
$translation = $media->getTranslation($langcode);
\Drupal::queue('media_entity_thumbnail')
->createItem(['id' => $translation->id()]);
\Drupal::logger('my_module')
->notice("Queued thumbail update for media entity " . $id . " " . $langcode);
}
}
}
catch (\Throwable $e) {
\Drupal::logger('my_module')
->error("Error queuing thumbail update for media entity " . $id . ": " . $e->getMessage());
}
};

return my_module_batch_updater($sandbox, $jobsLoader, $jobProcessor, 'media thumbnails queued');
}

--

--