Search code examples
phpwordpresswoocommercethumbnailscart

Display a custom thumbnail for a specific product ID in Woocommerce cart


In Woocommerce, I would like to change a specific cart item thumbnail with a personalized image. I can change the image, but it change all cart item thumbnails.
I only want to change the image of a specific product ID.

How can I do this?

Here is the code I'm using:

add_filter( 'woocommerce_cart_item_thumbnail', 'change_woocommerce_cart_item_thumbnail', 10, 3 ); 

function change_woocommerce_cart_item_thumbnail( $thumbnail, $cart_item, 

    $cart_item_key ) { 

    $cart = WC()->cart->get_cart();

    foreach( $cart as $cart_item ){

        $product = wc_get_product( $cart_item['product_id'] );

        if($cart_item['product_id'] == 75){

        echo  'New Image Here';

        }
    }

};

enter image description here

Any help please.


Solution

  • You don't need a foreach loop because the $cart_item is already included as an argument in the function. The following code will work for all product types and will allow you yo have a custom thumbnail for a specific product in cart page:

    add_filter( 'woocommerce_cart_item_thumbnail', 'change_woocommerce_cart_item_thumbnail', 20, 3 ); 
    function change_woocommerce_cart_item_thumbnail( $thumbnail, $cart_item, $cart_item_key ){ 
        // HERE your targeted product ID
        $targeted_id = 75;
    
        if( $cart_item['product_id'] == $targeted_id || $cart_item['product_id'] == $targeted_id ){
            echo  'New Image Here';
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.