Magento 2 PHP Foreach Loop Help

historymagento2ordersPHPproducts

I'm trying to display the images of products on each order item, so far I have the image pulling through but it's only one of 3 product images.

It's also displaying them on every order in the order history, but they should only display the correct images per order.

Below is my code, any help is much appreciated.

<?php $_orders = $block->getOrders(); ?>
  <?php if ($_orders && count($_orders)): ?>
    <div class="myOrders">
      <h2>My Orders</h2>
        <div class="order">
          <?php foreach ($_orders as $_order): ?>
            <?php
              $orderId = $_order->getId();
               $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);
               $items = $order->getAllItems();
               foreach ($items as $itemId => $_item){
                 $_item->getProductId();
                 $_item->getName();
                 $_item->getPrice();
                 $_item->getSku();
                 $_item->getQtyToInvoice();
                 $_product = $_item->getProduct($_item->getProductId());
                 $imageBlock =  $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct');
                 $productImages[] = $imageBlock->getImage($_product, 'category_page_grid');
               }
             ?>
             <div class="row">
               <div class="col-md-4">
                 <h4><?= /* @escapeNotVerified */ $block->formatDate($_order->getCreatedAt()) ?></h4>
               </div>
               <div class="col-md-4">
                 <h4><?= /* @escapeNotVerified */ $_order->getRealOrderId() ?></h4>
                </div>
                <div class="col-md-4">
                  <h4><?= /* @escapeNotVerified */ $_order->getStatusLabel() ?></h4>
                </div>
                <div class="col-md-12">
                  <?php foreach($productImages as $productImage): ?>
                    <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $productImage->toHtml()  ?></a>
                  <?php endforeach; ?>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
    <?php endif; ?>

EDIT

After following one of the solutions on this post I've now got all images pulling through but they are being duplicated on each orders.

See screenshot:
enter image description here

Kind of hard to see I know but the second order in the order history also has the first orders product images which don't exist in that order, so therefore should not be displaying.

Best Answer

  1. Please don't use directly the objectManager in your phtml, do instead some functions in your block, then you get them is you phtml exemple: $block->getFuntion();

  2. For all products images, try $images = $_product->getMediaGalleryImages();

  3. You loop the images:

    foreach($images as $image) {
        echo $image->getUrl();
    }
    
Related Topic