问题描述
我正在为我的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 );
}
}
现在应该可以工作。