0

这是一个自我问答

我需要一种方法来巧妙地构建一个 key=>value 数组,其中包含购物车中某个项目的所有变体。可用的 Woo 函数都返回一个字符串。

4

1 回答 1

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>';
    }
}
于 2015-09-24T22:00:34.540 回答