仅当产品存在于 Woocommerce 订单视图中时才添加订单商品图片

Add order item image only if the product exist on Woocommerce order view

在 woocommerce 我的帐户查看订单页面上,我能够使用此答案代码添加产品图片:

但我有一个问题进口订单相关,其中产品不存在.

因此,在查看这些订单时会出现空白页错误。

知道如何避免这个问题吗?

所以如果我理解得很好,订单中的产品有时可能不存在于 Woocommerce 中。此代码版本测试产品是否存在,如果不存在,则仅 return 订单项名称。

尝试以下操作:

// Display the product thumbnail in order view pages
add_filter( 'woocommerce_order_item_name', 'display_product_image_in_order_item', 20, 3 );
function display_product_image_in_order_item( $item_name, $item, $is_visible ) {
    // Targeting view order pages only
    if( is_wc_endpoint_url( 'view-order' ) ) {
        // Get the WC_Product object (from order item)
        $product   = $item->get_product(); 

        // Testing if the product exist in Woocommerce <== UPDATE
        if( $product && is_object( $product ) ) {
            // Get the product thumbnail (from product object)
            $thumbnail = $product->get_image(array( 36, 36)); 
            // Avoiding empty thumbnail (updated)
            if( $product->get_image_id() > 0 )
                $item_name = '<div class="item-thumbnail">' . $thumbnail . '</div>' . $item_name;
        } else {
            // When product doesn't exist, we get the name from the order item (with no thumbnail)
            $item_name = $item->get_name();
        }
    }
    return $item_name;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。希望有用。