WooCommerce:获取购物车项目变体的键=>值数组
WooCommerce: Get a key=>value array of a cart items variations
这是自问自答
我需要一种方法来巧妙地构建一个键=>值数组,其中包含购物车中某个项目的所有变体。可用的Woo函数都是return一个字符串。
这个函数接受一个购物车项目,returns一个键=>值数组。
放在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>';
}
}
这是自问自答
我需要一种方法来巧妙地构建一个键=>值数组,其中包含购物车中某个项目的所有变体。可用的Woo函数都是return一个字符串。
这个函数接受一个购物车项目,returns一个键=>值数组。
放在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>';
}
}