Set image field programatically


Using an image field with entity metadata wrapper is a little bit more tricky than the usual text fields.

Anyway, it is pretty simple.

The main difference is to upload the image prior to adding it to the field.

</> CopyGet raw version
  1. // First we have to upload the image to the public directory.
  2. $file_path = file_save_data(file_get_contents('/my_local_path/img1.jpg'), 'public://remote_name.jpg');
  4. // The wrapper can be created from a existing node or a new one. Once the wrapper is created, the usage is the same.
  5. // For example, for updating the existing node 55.
  6. $wrapper = entity_metadata_wrapper('node', 55);
  8. // We are updating an image field called field_banner_button_image.
  9. $wrapper->field_banner_button_image->file->set($file_path);
  11. // And save the node
  12. $wrapper->save();