skip to Main Content

All the thumbnails in the cart are run through the following woocommerce_cart_item_thumbnail filter:

$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

Any idea how to add a custom class to the <img> tag of the thumbnail through a function in the functions.php file of my child theme?

2

Answers


  1. you can simply find and replace the class

    add_filter( 'woocommerce_cart_item_thumbnail', 'custom_class_woocommerce_cart_item_thumbnail_filter', 10, 3 );
    
    function custom_class_woocommerce_cart_item_thumbnail_filter( $product_image, $cart_item, $cart_item_key ){
        $product_image = str_replace('class="', 'class="your-class ', $product_image);
        return $product_image;
    }
    
    Login or Signup to reply.
  2. You can specify class in attr argument of get_image function like this

    $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(null, array('class' => 'my-custom-image-class')), $cart_item, $cart_item_key );
    

    get_image function accepts 3 arguments

    /**
         * Returns the main product image.
         *
         * @param  string $size (default: 'woocommerce_thumbnail').
         * @param  array  $attr Image attributes.
         * @param  bool   $placeholder True to return $placeholder if no image is found, or false to return an empty string.
         * @return string
         */
        public function get_image( $size = 'woocommerce_thumbnail', $attr = array(), $placeholder = true ) {
            $image = '';
            if ( $this->get_image_id() ) {
                $image = wp_get_attachment_image( $this->get_image_id(), $size, false, $attr );
            } elseif ( $this->get_parent_id() ) {
                $parent_product = wc_get_product( $this->get_parent_id() );
                if ( $parent_product ) {
                    $image = $parent_product->get_image( $size, $attr, $placeholder );
                }
            }
    
            if ( ! $image && $placeholder ) {
                $image = wc_placeholder_img( $size, $attr );
            }
    
            return apply_filters( 'woocommerce_product_get_image', $image, $this, $size, $attr, $placeholder, $image );
        }
    

    In second $attr argument you can specify img tag attributes including class, if you defined your own custom thumbnail size, instead of passing null in first argument you can pass it, like this

    $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image('my-custom-thumbnail-size', array('class' => 'my-custom-image-class')), $cart_item, $cart_item_key );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search