Search code examples
phpwordpresswoocommercethumbnailsorders

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


On woocommerce My account view order pages I was able to add the product image using this answer code:
Add the product image to Woocommerce my account order view

But I have an issue related to imported orders where the product doesn’t exist.

So this make an error with a blank page, when viewing those orders.

Any idea on how to avoid this problem?


Solution

  • So If I understand well, the products in the order might not exist in Woocommerce sometimes. This code version test if the product exist and if not it only return the order item name.

    Try the following:

    // 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;
    }
    

    Code goes in function.php file of your active child theme (or active theme). I hope it will work.