7

I need to insert ATL tag for catalog products images programmatically. Is there any way to do it?

1
  • Yes You can, but tell me which page and where you need to add it? Dec 16, 2019 at 5:48

1 Answer 1

0

You can do this via the API interface Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface. You can add the image via the create() method, or update an existing entry via the update() method. Both methods require an instance of \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface, this interface has the setLabel() function that allows you to set the ALT tag for a product image.

I'm using a custom function to create images, it uses the above interfaces as factories. Updating an existing label/ALT tag works in the same way, but then using the update() function.

/**
 * Add image to product by SKU
 */
public function addImage(
    string $sku,
    string $filePath,
    array $imageTypes,
    string $destinationName,
    string $label = '',
    bool $disabled = false
): void {
    // Basic image data
    $data = file_get_contents($filePath);
    $base64 = base64_encode($data);
    $pathInfo = pathinfo($filePath);
    $fileExtension = strtolower($pathInfo['extension']);

    // Create media image
    $mediaImage = $this->mediaGalleryFactory->create();
    $mediaImage->setTypes($imageTypes);
    $mediaImage->setLabel($label);
    $mediaImage->setMediaType('image');
    $mediaImage->setDisabled($disabled);

    // Create content
    $content = $this->imageContentFactory->create();
    $content->setBase64EncodedData($base64);
    $content->setType("image/{$fileExtension}");
    $content->setName($destinationName);

    // Assign content to media and save image to product
    $mediaImage->setContent($content);
    $this->mediaGalleryManagement->create($sku, $mediaImage);
}

Constructor:

public function __construct(
    ImageContentInterfaceFactory $imageContentFactory,
    ProductAttributeMediaGalleryManagementInterface $mediaGalleryManagement,
    ProductAttributeMediaGalleryEntryInterfaceFactory $mediaGalleryFactory,
) {
    $this->mediaGalleryFactory = $mediaGalleryFactory;
    $this->mediaGalleryManagement = $mediaGalleryManagement;
    $this->imageContentFactory = $imageContentFactory;
}

You can set the store view using the setCurrentStore($storeCode) function from StoreManagerInterface

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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