Get parent product thumbnail filter in WooCommerce Cart and Checkout Page

2.4k views Asked by At

I'm wondering if there's a way to display the parent product thumbnail for all child products in the cart and checkout pages in WooCommerce. Is there a filter for doing something like this?

1

There are 1 answers

2
helgatheviking On

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

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

However, if a variation does not have its own thumbnail, WooCommerce will automatically show its parent's thumbnail:

/**
 * Gets the main product image.
 *
 * @param string $size (default: 'shop_thumbnail')
 * @return string
 */
public function get_image( $size = 'shop_thumbnail', $attr = array() ) {
    if ( $this->variation_id && has_post_thumbnail( $this->variation_id ) ) {
        $image = get_the_post_thumbnail( $this->variation_id, $size, $attr );
    } elseif ( has_post_thumbnail( $this->id ) ) {
        $image = get_the_post_thumbnail( $this->id, $size, $attr );
    } elseif ( ( $parent_id = wp_get_post_parent_id( $this->id ) ) && has_post_thumbnail( $parent_id ) ) {
        $image = get_the_post_thumbnail( $parent_id, $size , $attr);
    } else {
        $image = wc_placeholder_img( $size );
    }
    return $image;
}

If you aren't seeing this, then you possibly have outdated theme templates.

EDIT

With further information, you are apparently referring to grouped products. You can always tell if a product is "grouped" as its post_parent is set to the product ID of the grouped product. A top-level product as a post_product of 0. You can find the post_parent information in the data passed to the first filter I mentioned: woocommerce_cart_item_thumbnail to come up with the following:

add_filter( 'woocommerce_cart_item_thumbnail', 'so_30736886_cart_item_thumbnail', 10, 3 );
function so_30736886_cart_item_thumbnail( $image, $cart_item, $cart_item_key ){
    if( isset( $cart_item['product_id'] ) && isset( $cart_item['data'] ) && $cart_item['data']->post->post_parent > 0 ){
        $_parent = wc_get_product( $cart_item['data']->post->post_parent );
        $image = $_parent->get_image();
    }

    return $image;
}

If a product has a post_parent then we get the the thumbnail for the parent "Group" product.