Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Modify Cart Item Images for Specific Product Categories in WooCommerce Cart and Checkout Blocks?

WooCommerce customizations help a lot to make your products align with the marketing strategies. This is one such kind of customization where you can modify cart item images for specific product categories in the Cart and Checkout Blocks. This is useful in scenarios where a store owner has not set product images of a particular category and wants to display dynamic images for those specific product categories. Let’s see how this can be achieved with a simple code snippet.

Solution: Modify Cart Item Images for Specific Product Categories

The following snippet replaces the default cart item images with a dynamically generated image for products belonging to a specific category.

add_filter(
  'woocommerce_store_api_cart_item_images',
  function ($product_images, $cart_item, $cart_item_key) {
      $category_id = 91; // Change this to your target category ID
      
      // Get the product object
      $product = wc_get_product($cart_item['product_id']);
      
      // Check if the product belongs to the specific category
      if (has_term($category_id, 'product_cat', $product->get_id())) {
          $image_path = "https://picsum.photos/seed/$cart_item_key/200";
          return [
              (object)[
                  'id'        => (int) 0,
                  'src'       => $image_path,
                  'thumbnail' => $image_path,
                  'srcset'    => '',
                  'sizes'     => '',
                  'name'      => 'Random product image',
                  'alt'       => 'Random product image',
              ]
          ];
      }

      // Return original images for other products
      return $product_images;
  },
  10,
  3
);

Output

When a customer adds products of the specified category ID to the cart, the product will be displayed with a random product image. This ensures that even if a product image is missing, a placeholder is used instead.

How to Modify Cart Item Images for Specific Product Categories in WooCommerce Cart and Checkout Blocks? - Tyche Softwares

Since the WooCommerce Cart and Checkout Blocks are less customizable compared to the Classic WooCommerce layout, we understand the need for tailored solutions. That’s why we have another useful customization specifically for Checkout Blocks. Adding quantity fields on WooCommerce pages, including both Classic and Checkout Blocks, allows customers to adjust product quantities directly on the Checkout blocks page can lead to a smoother checkout process.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Newest
Oldest
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x