phpwordpressimagewoocommercefallback

WooCommerce get first gallery image as fallback, if post thumbnail is missing and at least the placeholder image


I have a problem to receive the first image of the woocommerce gallery, if the post thumbnail is missing. I want to show the post thumbnail, if this is missing, the first image of the WooCommerce gallery and at least the placeholder image, if all is missing.

I found this function in the WooCommerce Codex, but I don´t come on an satisfying solution. Maybe someone can help me to receive an good solution

function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $deprecated1 = 0, $deprecated2 = 0 ) {
        global $post;
        $image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );

        if ( has_post_thumbnail() ) {
            $props = wc_get_product_attachment_props( get_post_thumbnail_id(), $post );
            return get_the_post_thumbnail( $post->ID, $image_size, array(
                'title'  => $props['title'],
                'alt'    => $props['alt'],
            ) );
        } elseif ( wc_placeholder_img_src() ) {
            return wc_placeholder_img( $image_size );
        }
    }
}

Solution

  • So, I found myself an soultion. Is not as perfect as I wished, but it works. I post this this answer, if someone is searching for an similar solution. So, this could be an way:

    /* GET PRODUCT IMAGE WITH GALLERY FALLBACK
    ================================================== */
    if ( ! function_exists( 'zet_get_prod_image_fallback_gallery' ) ) {
        function zet_get_prod_image_fallback_gallery() {
    
            global $post, $woocommerce, $product;
            $image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );
            $thumb_gallery_ids = $product->get_gallery_attachment_ids();
    
            if ( has_post_thumbnail() || $thumb_gallery_ids ) {
    
                if ( has_post_thumbnail() ) {
                    $image_id = get_post_thumbnail_id();
                } else {
                    $image_id = $thumb_gallery_ids[0];
                }
    
                $thumb_image = wp_get_attachment_url( $image_id, apply_filters( 'single_product_small_thumbnail_size', 'shop_thumbnail' ) );
                $image_html = '<img src="'.$thumb_image.'" />';
    
                echo $image_html;
    
            // Get the Placeholder image
            } elseif ( wc_placeholder_img_src() ) {
                echo wc_placeholder_img( $image_size );
            }           
        }
    }
    

    For users who are not so familiar with wordpress: add this snippet to your functions.php If you want to use this fallback for your whole shop -> change the function woocommerce_template_loop_product_thumbnail() in woocommerce/content-product.php to zet_get_prod_image_fallback_gallery(). Hope it helps!