Woocommerce:在购物车页面上显示产品变化描述 [英] Woocommerce: Display Product Variation Description on Cart page
问题描述
我正在尝试在购物车中显示我的产品版本描述.我已尝试将此代码插入 cart.php
模板中:
I'm trying to display my product variation description in my Cart. I have tried inserting this code in the cart.php
template:
if ( $_product->is_type( 'variation' ) ) {echo $_product->get_variation_description();}
通过遵循本文档 https://docs.woocommerce.com/document/template-structure/
但是它仍然没有显示出来.
But it's still not showing up.
不确定在这里我在做什么错.
Not sure what I'm doing wrong here.
有人可以帮忙吗?
谢谢
推荐答案
WooCommerce版本3+的更新兼容性
自WooCommerce 3起, get_variation_description()
> 现在已弃用,并由WC_Product
方法 get_description()
.
Since WooCommerce 3, get_variation_description()
is now deprecated and replaced by the WC_Product
method get_description()
.
要在购物车中获取产品项变体说明 (筛选变体产品类型条件),您有 2种可能性(可能更多) …):
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模板显示版本描述.
在两种情况下,您都不需要在代码中使用
foreach
循环(如前所述),因为它已经存在.因此,代码将更加紧凑.
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
钩子:
Case 1 - using woocommerce_cart_item_name
hook:
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;
}
在这种情况下,描述仅显示在标题和变体属性值之间.
In this case the description is just displayed between the title and the variation attributes values.
此代码会出现在您活动的子主题(或主题)的function.php文件中,也可能会出现在任何插件文件中.
案例2 -使用 cart/cart.php
模板(根据您的评论更新).
Case 2 - Using cart/cart.php
template (Update as per your comment).
您可以选择显示此描述的位置(2个选择):
You can chose where you want to display this description (2 choices):
- 标题之后
- 标题和变体属性值之后.
因此,您将根据自己的选择,将这段代码插入第86或90行的cart.php模板中:
So you will insert this code on cart.php template around line 86 or 90 depending on your choice:
// 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, '3.0', '<' ) ? $product_item->get_variation_description() : $product_item->get_description();
if( ! empty( $description ) ) {
// '<br>'. could be added optionally if needed
echo __( 'Description: ', 'woocommerce' ) . $description;;
}
}
所有代码都经过测试并且功能齐全
这篇关于Woocommerce:在购物车页面上显示产品变化描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!