How to create media entities and attach them to paragraphs in Drupal 8 & 9
Code snippet that can be used to create media entities and attach them to paragraphs in Drupal 8 & 9.
$directory = public://media;
$url = 'https://example.com/photo.jpg';
if(file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
$file = system_retrieve_file(trim($url), $directory, true);
}
$media = Media::create([
'bundle' => 'image',
'uid' => '0',
'field_media_image' => [
'target_id' => $file->id(),
],
]);
$media->setPublished(TRUE)->save();
$paragraph = Paragraph::create([
'type' => 'image',
'field_media' => array(
'target_id' => $media->id(),
)
]);
$paragraph->save();