Get default placeholder image url in template file in magento 2

Get default placeholder image url in template file in magento 2

Hi guys,

Today we are going to see how we can get the default placeholder image url in magento 2. There comes many situation where we need to get the default placeholder image of the product. So below is how we can achieve that.

If you check your store settings you will find option of Product Image place holders, you can change your default placeholder from there.

Stores > Configuration > Catalog > Catalog > Product Image Placeholders

The better approach for achieving this would be calling a function on the template file which is defined on your block and performing the operation on that block file. We can simply do that as follows:

On you block file add the code:

protected $_storeConfig;

protected $_storeManager;

public function __construct
(
---
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
\Magento\Store\Model\StoreManager $storeManager
---

){
---
$this->_storeConfig = $scopeConfig;
$this->_storeManager = $storeManager;
---
}

public function getPlaceholderImage(){
//getting the media base url
$mediaBaseUrl = $this ->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA );
$placeholderPath = $this->_storeConfig->getValue('catalog/placeholder/image_placeholder');//Base Image
//full url of the placeholder image
$fullUrl = $mediaBaseUrl.'catalog/product/placeholder/'.$placeholderPath;

return $fullUrl;

}

 

Now in your template file call:

$block->getPlaceholderImage();

 

That’s it. Above mentioned approach is the best way of getting the image URL, however you can also do it the dirty way i.e using object manager. In this method you don’t have to use the dependency injection method on the constructor, All the classes could be instantiated on the template file.

Hope this will help.