WooCommerce购物车对象使用以及方法函数概括

本站所有文章均为博主人工写作,绝无AI辅助成分,请放心参阅。

WooCommerce二次开发中,经常会需要对购物车进行改造,甚至有时候会需要重写购物车页面,所以就有必要把WooCommerce的购物车提供的接口方法做一下整理。本文对我在最近的一些项目中使用过的方法进行简要的记录。

首先,在调用任何购物车方法之前,先要检查当前页面环境对购物车对象是否可用:

1
2
3
4
if ( is_null( WC()->cart ) ) {
wc_load_cart();
}
WC()->cart->get_cart();

常用的条件函数,返回true/false

1
2
3
4
5
6
7
8
9
10
//检查购物车是否有商品
WC()->cart->is_empty();
//检查购物车是否需要付费,如果费用为0则返回false
WC()->cart->needs_payment();
//检查购物车中是否已经记录收货地址
WC()->cart->show_shipping();
//检查是不是需要寄送(用于计算运费的情况)
WC()->cart->needs_shipping();
//检查是不是有折扣,如果后台减了价格,这里会返回true
WC()->cart->has_discount();

获取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* Author: Brain - blog.brain1981.com */
//返回购物车商品总数
WC()->cart->get_cart_contents_count();
//返回购物车小计
WC()->cart->get_cart_subtotal();
//返回总运费
WC()->cart->get_shipping_total();
//返回使用的优惠券,返回数组,内容包含优惠券对象和优惠码
WC()->cart->get_coupons();
//返回使用的优惠券,返回数组,内容仅包含优惠码
WC()->cart->get_applied_coupons();
返回指定优惠码在当前购物车中获得的折扣金额
WC()->cart->get_coupon_discount_amount( 'coupon_code' );
//返回总折扣金额,这俩其实等于同一个方法
WC()->cart->get_discount_total();
WC()->cart->get_cart_discount_total();
//返回购物车总金额,包含了折扣和运费
WC()->cart->get_total();
WC()->cart->tota;

获取用户的地址信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* Author: Brain - blog.brain1981.com */
//获取用户对象
WC()->cart->get_customer();
//获取用户的地址信息
WC()->cart->get_customer()->get_billing_first_name();
WC()->cart->get_customer()->get_billing_last_name();
WC()->cart->get_customer()->get_billing_company();
WC()->cart->get_customer()->get_billing_email();
WC()->cart->get_customer()->get_billing_phone();
WC()->cart->get_customer()->get_billing_country();
WC()->cart->get_customer()->get_billing_state();
WC()->cart->get_customer()->get_billing_postcode();
WC()->cart->get_customer()->get_billing_city();
WC()->cart->get_customer()->get_billing_address();
WC()->cart->get_customer()->get_billing_address_2();
WC()->cart->get_customer()->get_shipping_first_name();
WC()->cart->get_customer()->get_shipping_last_name();
WC()->cart->get_customer()->get_shipping_company();
WC()->cart->get_customer()->get_shipping_country();
WC()->cart->get_customer()->get_shipping_state();
WC()->cart->get_customer()->get_shipping_postcode();
WC()->cart->get_customer()->get_shipping_city();
WC()->cart->get_customer()->get_shipping_address();
WC()->cart->get_customer()->get_shipping_address_2();

常用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* Author: Brain - blog.brain1981.com */
//添加指定的产品到购物车,如果是添加普通产品只需要$product_id和$quantity即可,添加可变产品比较复杂,会另外写博客介绍
WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation);
//修改购物车中商品的数量
WC()->cart->set_quantity( $item_key, $quantity );
//删除购物车中的商品
WC()->cart->remove_cart_item( $item_key );
//使用优惠券,参数就是优惠码
WC()->cart->apply_coupon( $coupon_code );
//删除优惠券,参数也是优惠码
WC()->cart->remove_coupon( $coupon_code );
//删除所有的优惠券
WC()->cart->remove_coupons();
//重新计算购物车价格
WC()->cart->calculate_totals();

方法中,有一些注意点,add_to_cart、set_quantity以及remove_cart_item,这些对商品增减的方法执行后,购物车会自动调用calculate_totals计算价格。但apply_coupon和remove_coupon这些对优惠券的方法执行后,需要自己执行一遍calculate_totals计算价格。

此外,set_quantity和remove_cart_item的参数$item_key,是当前购物车中商品对应的键值,这些键是通过JSON格式存储的,需要通过WooCommerce自己封装的方法获取:
对于普通商品,已知$product_id,可通过以下方法获得$item_key

1
2
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$item_key = WC()->cart->find_product_in_cart( $product_cart_id );

对可变商品,已知$variation_id,则是通过遍历方法获取

1
2
3
4
5
6
7
8
/* Author: Brain - blog.brain1981.com */
foreach ( WC()->cart->get_cart() as $item_key => $item ) {
	// If the targeted variation id is in cart
	if ( $item['variation_id'] == $variation_id ) {
		$item_key ... 
		break;
	}
}

通过以上总结的常用方法组合,我们大致就可以开发出自己的购物车程序了,列举一个常用的列出购物车商品清单的函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* 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;
}

主要参考:WooCommerce官方文档页面

全文完

本站所有文章均为原创,欢迎转载,请注明文章出处:https://blog.brain1981.com/2851.html。百度和各类采集站皆不可信,搜索请谨慎鉴别。技术类文章一般都有时效性,本人习惯不定期对自己的博文进行修正和更新,因此请访问出处以查看本文的最新版本。

关注我们的微信公众号-JennyStudio 本站记录了近几年的工作中遇到的一些技术问题和解决过程,“作品集”还收录了本人的大部分作品展示。除了本博客外,我们的工作室网站 – JennyStudio,内有更多作品回顾和展示。
您也可以扫描左边的二维码,关注我们的微信公众号,在微信上查看我们的案例。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注