Thursday, October 29, 2020

Woocommerce: Only add the order item image when the product exists in the Woocommerce Order view

 https://www.thinbug.com/q/51848205


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

No comments: