5

I need to retrieve image's url in phtml from pub/media dir, the same image that i used in a static wysiwig block retrieved with {{media url="path/to/image.jpg"}}.

I know $block->getViewFileUrl(), but it takes images from app/code or app/design.

Is there a same easy way?

2

Call Function in Block file,

 Class Test{
        protected $storeManager;
        public function __construct(
                \Magento\Store\Model\StoreManagerInterface $storeManager,
              ../////
            ) {
                $this->storeManager = $storeManager;
                ..////
            }

        public function getMediaimg(){
            $folderName = 'cusotomimg';
            $imgname = 'abc.jpg';
            $path = $folderName . '/' . $imgname;
            return $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $path;
        }
    }

Now call inside phtml file,

   <?php echo $block->getMediaimg(); ?>

Directly using objectmanager, this is not recommended way but you can check its using directly in phtml file instead of using objectmanager you can using Block file

$om = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $om->get('Magento\Store\Model\StoreManagerInterface');
$folderName = 'cusotomimg';
$imgname = 'abc.jpg';
$path = $folderName . '/' . $imgname;
echo $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $path;
1

in block file

public function getMediaDirectoryUrl(){

       $media_dir = $this->objectManager->get('Magento\Store\Model\StoreManagerInterface')
          ->getStore()
          ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

       return $media_dir;
}

in phtml file

 $block->getMediaDirectoryUrl();

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.