如何解决WooCommerce从订单项获取产品变体属性名称和值
我正在为我的WooCommerce商店创建自定义的“谢谢”页面,在这里我可以正确显示购物车商品的属性和值,但是在“谢谢”页面中,我无法显示可以帮我吗?
迷你购物车项目的工作代码:
$items = WC()->cart->get_cart();
foreach($items as $item => $values) {
$cart_item = WC()->cart->cart_contents[ $item ];
$variations = wc_get_formatted_cart_item_data( $cart_item );
if( $cart_item['data']->is_type( 'variation' ) ){
$attributes = $cart_item['data']->get_attributes();
$variation_names = array();
if( $attributes ){
foreach ( $attributes as $key => $value) {
$variation_key = end(explode('-',$key));
$variation_names[] = ucfirst($variation_key) .' : '. $value;
}
}
echo implode( '<br>',$variation_names );
}
}
输出类似
Color : Red
Size : 4mm
我想在“谢谢”页面中显示相同的内容,因此我将其重新编码为订单格式并循环遍历不起作用
$items = $order->get_items();
foreach ($items as $item_key => $item) {
$product = $item->get_product();
if( $product->is_type( 'variation' )){
$attributes = $product->get_variation_attributes();
$variation_names = array();
if( $attributes ){
foreach ( $attributes as $key => $value) {
$variation_key = end(explode('_',$variation_names );
}
}
解决方法
使用$item->get_product()
从产品品种上使用WC_Product
方法从订单商品中获取当前get_attributes()
对象,而不是get_variation_attributes()
只能用于父变量产品。
$order_items = $order->get_items();
foreach ($order_items as $item_key => $item) {
$product = $item->get_product(); // Get the WC_Product Object
if( $product->is_type( 'variation' ) ){
$attributes = $product->get_attributes();
$variation_names = array();
if( $attributes ){
foreach ( $attributes as $key => $value) {
$variation_key = end(explode('-',$key));
$variation_names[] = ucfirst($variation_key) .' : '. $value;
}
}
echo implode( '<br>',$variation_names );
}
}
现在应该可以工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。