2

我正在为我的 WooCommerce 商店制作自定义感谢页面,我可以在其中正确显示购物车项目的属性和价值,但在Thankyou 页面中我未能显示,你能帮我吗?

迷你购物车项目的工作代码:

$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('_', $key));
                $variation_names[] = ucfirst($variation_key) .' : '. $value;
            }
        }
        echo implode( '<br>', $variation_names );
    }
}
4

1 回答 1

2

用于使用产品变体上的方法从订单项目$item->get_product()中获取当前对象,而不是仅在父变量产品上使用。WC_Productget_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 );
    }
}

它现在应该可以工作了。

于 2020-11-02T17:58:50.643 回答