I'm trying to pull through the gallery images on the product page as I'm re doing the gallery. The code I'm using is:

<?php $_product = $block->getProduct(); ?>
<?php $gallery = $_product->getMediaGalleryImages(); ?>

<?php foreach ($gallery as $galleries): ?>
  <figure><?php echo $galleries ?></figure>
<?php endforeach; ?>

But this throughs back an error of "Object can't be converted to string"

Any ideas on how to fix this?


override the below template for getting gallery images url in product detail page


<?php /* @escapeNotVerified */ $json=$block->getGalleryImagesJson();
$array = json_decode($json,true);
foreach($array as $item)
    $imgurl = $item['full'];
    echo $imgurl;        

use this above method I rendered full image. you can able to get full,small,thumbnail images. If you want to know about what are the images type available, just var_dump($json).

| improve this answer | |
  • How do I get this to work on a custom.phtml page? as the Json returns Null? – Mark Aug 23 '16 at 10:49
  • I can't get you clearly what you ask. do you mean place the above script in other phtml? – Bilal Usean Aug 23 '16 at 10:55
  • yes. One that doesn't already exist so a new .phtml page that I will create an xml block for – Mark Aug 23 '16 at 10:58
  • simply change the first line enough :-) $json = $block->getLayout()->createBlock('\Magento\Catalog\Block\Product\View\Gallery')->getGalleryImagesJson(); – Bilal Usean Aug 23 '16 at 10:59
  • refer this link for how to call other blocks methods in template file :-) magento.stackexchange.com/questions/116022/… – Bilal Usean Aug 23 '16 at 10:59

Try bellow code for display product images on product detail page.

Add code to gallary.phtml

foreach($block->getGalleryImages() as $image){ ?>
    <?php if(!$block->isMainImage($image)):?>
        <img src="<?php echo $image->getData('medium_image_url') ?>">
    <?php endif; ?>
<?php } ?>

Let me know if you have any problem.

| improve this answer | |
  • How do I get this to work on a custom.phtml as the foreach argument comes back with "Invalid argument supplied for foreach()" ? – Mark Aug 23 '16 at 10:57
  • Yes if you want to get in your custom.phtml then you have to call block "Magento\Catalog\Block\Product\Gallery" for you cusotm.phtml and check it. i am not sure but try with this. – Suresh Chikani Aug 23 '16 at 11:09

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.