I have this simple code here that fetches the thumbnail image of the order on orders.php
template.
<div class="product-img-col">
<div class="product-img-list">
<?php foreach( $order->get_items() as $item_id => $item ) {
$product = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
echo $product->get_image();
}
?>
</div>
</div>
What I want to achieve is to separate the thumbnails by class if order contains 1 product or multiple products.
Example:
<div class="product-img-col">
<div class="single-product-img">
<!-- Insert code to fetch the product thumbnail for single order here -->
</div>
<div class="product-img-list">
<!-- Insert code to fetch the product thumbnails for orders with multiple products here -->
</div>
</div>
Is this possible? I know foreach function just fetches all the product thumbnails for that specific order. How do I alternate the code to add if condition
if the order # contains only 1 product and then fetch the product thumbnail.
EDIT: UPDATE
<div class="product-img-col">
<div class="<?php echo count( $order->get_items() ) > 1 ? 'product-img-list' : 'single-product-img'; ?>">
<?php foreach( $order->get_items() as $item_id => $item ) {
$product = $item->get_product();
echo $product->get_image();
}
?>
</div>
</div>
2
Answers
You can use the internal WooCommerce
get_item_count()
function to check how much items are in the order. You can implement this function in a ternary operator.<div class="<?php echo $order->get_item_count() > 1 ? 'product-img-list' : 'single-product-img'; ?>">
Also note that
$order->get_product_from_item( $item )
is deprecated. You should use$item->get_product()
instead. Which will also eliminate the use to add thewoocommerce_order_item_product
filter, as this is being called in theget_product()
function.You will also need a check on the
$product
variable. Right now your code will crash if it encounters orders with products that are no longer in your product catalog.So something like this:
Here is a working solution – single item:https://prnt.sc/HhclHKDpJ1YA multiple items: https://prnt.sc/Zb9MeWUlIw6v