如果缺少 post 缩略图并且至少是占位符图像,WooCommerce 会获取第一个图库图像作为后备

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

如果缺少 post 缩略图,我无法收到 woocommerce 画廊的第一张图片。我想显示 post 缩略图(如果缺少)、WooCommerce 画廊的第一张图片和至少占位符图片(如果全部丢失)。

我在 WooCommerce Codex 中找到了这个功能,但我没有找到令人满意的解决方案。也许有人可以帮助我获得一个好的解决方案

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 );
        }
    }
}

所以,我发现自己是一个灵魂。没有我希望的那么完美,但它确实有效。我 post 这个答案,如果有人正在寻找类似的解决方案。所以,这可能是一种方式:

/* 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 );
        }           
    }
}

对于不太熟悉 wordpress 的用户:将此代码段添加到您的 functions.php 如果你想为你的整个商店使用这个后备 -> 将 woocommerce_template_loop_product_thumbnail() 中的函数 woocommerce/content-product.php 更改为 zet_get_prod_image_fallback_gallery()。希望对您有所帮助!