John Davidson

php - Woocommerce how to get products images of recent orders

0 comments
Message:


The code below re-displays each image without resetting at each foreach loop.


For example it gives:



  • product 1 - image1

  • product 2 - image1+2

  • product 3 - image1+2+3 ...


How can I make sure that the pictures of the past products are not displayed again for the following products?


Expected result:



  • product 1 - image 1

  • product 2 - image 2

  • product 3 - image 3 ...


Thank you in advance, here is my code:


    <?php foreach ( $last_order->get_items() as $item ) : ?>
<?php
$product = $item->get_product(); // Get the WC_Product object (from order item)
$thumbnail = $product->get_image(array( 50, 50)); // Get the product thumbnail (from product object)
if( $product->get_image_id() > 0 ){
$item_name = '<div class="item-thumbnail">' . $thumbnail . '</div>' . $item_name;
}
echo $item_name . $item->get_name();?>
<?php endforeach;?>


My Answer:
You can achieve this by keeping track of the product images that have already been displayed and skipping them in the loop. Here is an example code snippet to help you achieve the expected result:

php
// Get recent orders
$orders = wc_get_orders( array(
'limit' => 5, // Get the 5 most recent orders
) );

foreach ( $orders as $order ) {
$order_id = $order->get_id();
$items = $order->get_items();

foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$product = wc_get_product( $product_id );
$product_image = $product->get_image();

// Check if the product image has already been displayed
if ( ! isset( $displayed_images[ $product_id ] ) ) {
echo 'Product ' . $product_id . ' - ' . $product_image . '
';
$displayed_images[ $product_id ] = true;
}
}
}


In this code snippet, we are using an array `$displayed_images` to keep track of the product images that have already been displayed. We check if the product image has already been displayed before displaying it in the loop. This way, each product image will only be displayed once.

Rate this post

5 of 5 based on 9592 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us