You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce如何获取最近订单商品图片并解决foreach循环图片累加问题

问题原因

核心是$item_name变量没有在每次循环开始时重置,上一轮循环拼接的图片内容会被保留到本轮,反复累加就出现了后续商品携带前面所有商品图片的问题。

修复方案

只需要在每次循环的起始位置将$item_name初始化为空字符串即可,修改后的代码如下:

<?php foreach ( $last_order->get_items() as $item ) : ?>
    <?php 
    // 每次循环先重置$item_name为空,避免上一轮内容残留
    $item_name = '';
    $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>';
    }
    echo $item_name . $item->get_name();?>
<?php endforeach;?>
补充说明
  • 原代码中$item_name = 缩略图 . $item_name的写法已优化,因为每次循环初始$item_name为空,不需要再拼接本身。
  • 如果存在商品没有设置缩略图的情况,$item_name会保持为空,也不会输出多余的空标签,符合常规业务逻辑。

内容的提问来源于stack exchange,提问作者Loris GFT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 03:12:04