【问题标题】:Get parent product thumbnail filter in WooCommerce Cart and Checkout Page在 WooCommerce 购物车和结帐页面中获取父产品缩略图过滤器
【发布时间】:2015-08-24 13:22:06
【问题描述】:

我想知道是否有一种方法可以显示 WooCommerce 中购物车和结帐页面中所有子产品的父产品缩略图。有没有过滤器可以做这样的事情?

【问题讨论】:

    标签: woocommerce


    【解决方案1】:

    购物车中的所有缩略图都经过woocommerce_cart_item_thumbnailfilter:

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

    但是,如果变体没有自己的缩略图,WooCommerce 将自动显示其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;
    }
    

    如果你没有看到这个,那么你可能有过时的主题模板。

    编辑

    有了更多信息,您显然指的是分组产品。您始终可以判断产品是否“分组”,因为其 post_parent 设置为分组产品的产品 ID。 post_product 为 0 的顶级产品。您可以在传递给我提到的第一个过滤器的数据中找到 post_parent 信息:woocommerce_cart_item_thumbnail 得出以下内容:

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

    如果产品有post_parent,那么我们将获得父“组”产品的缩略图。

    【讨论】:

    • 感谢您的回复。我实际上是为组中的每个链接产品设置特色图像。但特色图像是纯色 .jpg 以显示对应每个链接产品的颜色。但在购物车页面中,我想展示用其父特色图片替换子产品缩略图。到目前为止,似乎找不到任何人尝试这样做。
    • 我提到的第一个过滤器仍然与您的情况相关,并且可能将此信息添加到您的原始问题中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多