php – Woocommerce:在购物车页面上显示产品变化描述

我正在尝试在购物车中显示我的产品变体说明.我尝试在cart.PHP模板中插入此代码
if ( $_product->is_type( 'variation' ) ) {echo $_product->get_variation_description();}

按照此文档https://docs.woocommerce.com/document/template-structure/

但它仍然没有出现.

不知道我在这里做错了什么.

任何人都可以帮忙吗?

谢谢

UPDATE COMPATIBILITY for WooCommerce version 3+

由于WooCommerce 3,get_variation_description()现已弃用,并被WC_Product方法get_description()取代.

To get your product item variation description in cart (filtering variation product type condition),you have 2 possibilities (may be even more…):

>使用woocommerce_cart_item_name钩子显示变体描述,无需编辑任何模板.
>使用cart.PHP模板显示变体描述.

In both cases you don’t need to use in your code a foreach loop,as answered before,because it already exist. So the code will be more compact.

案例1 – 使用woocommerce_cart_item_name钩子:

add_filter( 'woocommerce_cart_item_name','cart_variation_description',20,3);
function cart_variation_description( $name,$cart_item,$cart_item_key ) {
    // Get the corresponding WC_Product
    $product_item = $cart_item['data'];

    if(!empty($product_item) && $product_item->is_type( 'variation' ) ) {
        // WC 3+ compatibility
        $descrition = version_compare( WC_VERSION,'3.0','<' ) ? $product_item->get_variation_description() : $product_item->get_description();
        $result = __( 'Description: ','woocommerce' ) . $descrition;
        return $name . '<br>' . $result;
    } else
        return $name;
}

在这种情况下,描述仅显示标题和变体属性值之间.

代码位于活动子主题(或主题)的function.PHP文件中,或者也可以放在任何插件文件中.

案例2 – 使用cart / cart.PHP模板(根据您的评论更新).

您可以选择要显示此说明的位置(2个选项):

>标题
>标题和变体属性值之后.

因此,您将根据您的选择在第86行或第90行的cart.PHP模板上插入此代码

// Get the WC_Product
$product_item = $cart_item['data'];

if( ! empty( $product_item ) && $product_item->is_type( 'variation' ) ) {
    // WC 3+ compatibility
    $description = version_compare( WC_VERSION,'<' ) ? $product_item->get_variation_description() : $product_item->get_description();
    if( ! empty( $description ) ) {
        // '<br>'. Could be added optionally if needed
        echo  __( 'Description: ','woocommerce' ) . $description;;
    }
}

所有代码都经过测试,功能齐全

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...