Native Magento 2 has four types of placeholder images called, small_image, image, thumbnail, and swatch_image.
Placeholder image URL is used when you want to display default images for a site.
Magento 2 gets a placeholder image URL using below simple code snippet.
I hope you are aware of, How to upload Placeholder images in Magento 2?
Create a Block file to programmatically get a placeholder image,
<?php
namespace Rbj\Training\Model;
use Magento\Catalog\Helper\ImageFactory;
use Magento\Framework\View\Asset\Repository;
class Placeholder
{
private Repository $assetRepos;
private ImageFactory $imageFactory;
public function __construct(
Repository $assetRepos,
ImageFactory $imageFactory,
) {
$this->assetRepos = $assetRepos;
$this->imageFactory = $imageFactory;
}
/**
* Get place holder image of a product for small_image
*
* @return string
*/
public function getPlaceHolderImage(): string
{
$imagePlaceholder = $this->imageFactory->create();
$smallImagePlaceHolder = $imagePlaceholder->getPlaceholder('small_image');
return $this->assetRepos->getUrl($smallImagePlaceHolder);
}
}
Call the Placeholder function below way,
<?php $placeholderUrl = $this->getPlaceHolderImage(); ?> <img src="<?php echo $placeholderUrl; ?>" alt="placeholder" />
Using the above way, You can get a small_image Placeholder image URL in Magento 2.
You can pass small_image, image, thumbnail, and swatch_image for a placeholder.

One Reply to “Get Placeholder image url in Magento 2.”
Comments are closed.