I had a problem adding a product Image Label programatically. Here's the code I used:

    $imageLabel1 = 'Test1';
    $imageLabel2 = 'Test2';
    $imageLabel3 = 'Test3';
    $product->setMediaGallery (array('images'=>array (), 'values'=>array ())) 
            ->addImageToMediaGallery('/test1.jpg', array('image'), false, false);
            ->addImageToMediaGallery('/test2.jpg', array('thumbnail'), false, false);
            ->addImageToMediaGallery('/test3.jpg', array('small_image'), false, false);

Where i can set $imageLabel1 - 2 - 3?


Try this:

$imageLabel1 = 'Test1';
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {


The code above is the only way to set label for a media gallery entry, because there's no direct API from Product to set them.

It also means, you still using your current code to set new media gallery, then use the code above to update label for it after $product->save() (another mean, you have to save() product twice)

Pseudo code

public function addImageToMediaGallery(Product $product) {
    // your code

public function updateImageLabel(Product $product, $label) {
    // my code

public function updateProduct() {
    // ....

    foreach ($labels as $label) {

    // ....
  • Thanx, but where can I set this code? I mean below my code? Is it working with multiple image set? see my updated question@ Toan – Magento2 Devloper Aug 31 '17 at 5:34
  • @Magento2Devloper I updated my question. Hope it makes more sense to you now :) – Toan Nguyen Aug 31 '17 at 7:00
  • It's working but image label not set image wise. ex - test1.jpg in set imageLabel3. any idea regarding this? – Magento2 Devloper Aug 31 '17 at 8:17
  • @Magento2Devloper I don't understand what you mean. Can you update it in your question again? – Toan Nguyen Aug 31 '17 at 8:33
  • I need to set image label like ex - test1.jpg in set 'Test1' Label. in your code set test1.jpg in 'Test3' label. now understand? – Magento2 Devloper Aug 31 '17 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.