/* Author: Brain - blog.brain1981.com */
function brain1981_rest_wc_cart_list($request = null) {
if ( is_null( WC()->cart ) ) {
wc_load_cart();
}
WC()->cart->get_cart();
$resaults = [];
if( WC()->cart->is_empty() ){//如果没有物品则直接返回
return $resaults;
}
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$productID = $cart_item['product_id'];
$variationID = $cart_item['variation_id'];
if($variationID == 0){ //普通产品
$thumbnailID = get_post_meta( $productID, '_thumbnail_id', true);
$attachment = wp_get_attachment_image_src($thumbnailID, 'woocommerce_thumbnail' );
$product = wc_get_product($productID);
$stock = $product->get_stock_quantity();
} else { //可变产品
$variation = new WC_Product_Variation( $variationID );
$image_id = $variation->get_image_id();
$attachment = wp_get_attachment_image_src($image_id, 'woocommerce_thumbnail' );
$stock = $variation->get_stock_quantity();
}
if($attachment){
$image = $attachment[0];
} else {
$image = get_template_directory_uri()."/images/logo.png";
}
$product_name = get_the_title($cart_item['product_id']);
//整理影响变量的属性字段
$attr_arr = [];
if($variationID){
$variation = wc_get_product($variationID);
foreach( $cart_item['variation'] as $key => $value ){
$tax_slug = str_replace('attribute_','', $key);
$tax = get_taxonomy( $tax_slug );
if($tax){
$tax_name = $tax->labels->name; //exp "name": "产品 尺码",
}else{
$tax_name = urldecode($tax_slug);
}
$tax_name = str_replace('产品 ','', $tax_name);
$term = get_term_by('slug', $value, $tax_slug);
if($term){
$term_name = $term->name;
}else{
$term_name = $value;
}
$attr = array(
'name'=> $tax_name,
'value' => $term_name
);
array_push( $attr_arr, $attr);
}
}
$api_item = array(
'product_image' => $image,
'product_name' => $product_name,
'product_id' => $productID,
'variation_id' => $variationID,
'quantity' => $cart_item['quantity'],
'attributes' => $attr_arr,
'item_taxes' => $cart_item['line_tax_data'],
'subtotal_tax' => $cart_item['line_subtotal_tax'],
'total_tax' => $cart_item['line_tax'],
'subtotal' => $cart_item['line_subtotal'],
'total' => $cart_item['line_total'],
'stock' => $stock
);
array_push( $resaults, $api_item);
}
return $resaults;
}