WooCommerce:获取购物车商品变体的key =>值数组

时间:2015-09-24 22:00:35

标签: wordpress woocommerce cart variations

这是一个自我Q& A

我需要一种方法来巧妙地为购物车中商品的所有变体构建一个key =>值数组。可用的Woo函数都返回一个字符串。

1 个答案:

答案 0 :(得分:0)

此函数获取购物车项目,并返回key => value数组。

将其放在functions.php

/*
 * Get a cart product/item's variation as a key=>value pair
 */
    function store_get_cart_product_variations($cart_item) {
        $variations = WC()->cart->get_item_data($cart_item, true); 

        // Explode and trim
        $parts = explode(PHP_EOL, $variations);
        $parts = array_filter($parts);

        // Build a key=>value pair, trim any extra whitespace
        $variations = array();
        foreach($parts as $part) {
            list($key, $value) = explode(':', $part);
            $variations[trim($key)] = trim($value);
        }

        return $variations;
    }

然后就可以这样使用:

$cart_items = WC()->cart->get_cart();
foreach ( $cart_items as $cart_item_key => $cart_item ) {
    $variations = store_get_cart_product_variations($cart_item);        
    foreach($variations as $type => $value) {
        echo $type . ': ' . '<span class="value">' . $value .'</span>';
    }
}