wordpress WooCommerce:获取购物车项目变体的key=>value数组

pbgvytdp  于 2022-11-22  发布在  WordPress
关注(0)|答案(1)|浏览(163)

这是一个自我问答

我需要一种方法来为购物车中的商品创建一个key=〉value数组,所有可用的Woo函数都返回一个字符串。

oxiaedzo

oxiaedzo1#

这个函数接受一个购物车项目,并返回一个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>';
    }
}

相关问题