Hook for customizing product image thumbnail

I need a help on woo-commerce to override the cart product image thumbnail.
I am creating a plugin for customizing the product in the detail page and if we do “add to cart” it will be updated in the cart page with a customized thumbnail.

If any hook is available for overriding the image, please let me know.

Related posts

Leave a Reply

4 comments

  1. I’ve spent many hours searching for the answer also and even asked a Stackoverflow question (WooCommerce: change product image permalink with filter/action hook) which now happens to be duplicate (could not find this question prior to submitting my own).

    The answer:

    The hook is woocommerce_cart_item_thumbnail.
    So in your functions.php add

    function custom_new_product_image($a) {
    
        $class = 'attachment-shop_thumbnail wp-post-image'; // Default cart thumbnail class.
        $src = [PATH_TO_YOUR_NEW_IMAGE];
    
        // Construct your img tag.
        $a = '<img';
        $a .= ' src="' . $src . '"';
        $a .= ' class="' . $class . '"';
        $a .= ' />';
    
        // Output.
        return $a;
    
    }
    
    add_filter( 'woocommerce_cart_item_thumbnail', 'custom_new_product_image' );
    

    and your thumbnails will be replaced (more processing needed if you want to change each thumbnail individually).

  2. To change thumbnail image size of WooCommerce cart page you need next steps:

    1. In function.php create the size you need:

      if ( function_exists( 'add_image_size' ) ) {
          add_image_size( 'custom-thumb', 100, 100, true ); // 100 wide and 100 high
      }
      
    2. In cart.php which should be located in your_themewoocommercecartcart.php find

      $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image( 'custom-thumb' ), $cart_item, $cart_item_key );
      
  3. Please review the WooCommerce cart templates in woocommerce/templates/cart/cart.php.

    There is a clear filter woocommerce_cart_item_thumbnail for the product thumbnail in the cart.

    $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );
    
  4. Change ‘medium’ for your required image size:

    /**
     * Update cart product thumbnail
     */
    function woocommerce_cart_item_thumbnail_2912067($image, $cartItem, $cartItemKey)
    {
        $id = ($cartItem['variation_id'] !== 0 ? $cartItem['variation_id'] : $cartItem['product_id']);
        return wp_get_attachment_image(get_post_thumbnail_id((int) $id), 'medium');
    }
    add_filter('woocommerce_cart_item_thumbnail', 'woocommerce_cart_item_thumbnail_2912067', 10, 3);
    

    This results in your not having to update the core WooCommerce template files.