更新 3
从WooCommerce 3.7开始,您现在应该在实例对象上使用方法get_coupon_codes()
从订单中获取使用的优惠券,因为方法已弃用。WC_Abstract
WC_Order
get_used_coupons()
因此,您将在代码中替换:
foreach( $order->get_used_coupons() as $coupon_code ){
由:
foreach( $order->get_coupon_codes() as $coupon_code ){
然后,您可以获得优惠券详细信息,例如:
foreach( $order->get_coupon_codes() as $coupon_code ) {
// Get the WC_Coupon object
$coupon = new WC_Coupon($coupon_code);
$discount_type = $coupon->get_discount_type(); // Get coupon discount type
$coupon_amount = $coupon->get_amount(); // Get coupon amount
}
更新 2
首先,自WooCommerce 3以来,您再也无法访问WC对象属性。
您现在应该使用WC_Coupon
getter 方法从 Object 实例获取优惠券详细信息...WC_Coupon
在你的情况下,你必须使用get_discount_type()
方法或is_type('cash_back_fixed')
方法...
以下是执行此操作的方法:
// Get an instance of WC_Order object
$order = wc_get_order( $order_id );
// Coupons used in the order LOOP (as they can be multiple)
foreach( $order->get_used_coupons() as $coupon_code ){
// Retrieving the coupon ID
$coupon_post_obj = get_page_by_title($coupon_code, OBJECT, 'shop_coupon');
$coupon_id = $coupon_post_obj->ID;
// Get an instance of WC_Coupon object in an array(necessary to use WC_Coupon methods)
$coupon = new WC_Coupon($coupon_id);
// Now you can get type in your condition
if ( $coupon->get_discount_type() == 'cash_back_percentage' ){
// Get the coupon object amount
$coupon_amount1 = $coupon->get_amount();
}
// Or use this other conditional method for coupon type
if( $coupon->is_type( 'cash_back_fixed' ) ){
// Get the coupon object amount
$coupon_amount2 = $coupon->get_amount();
}
}
要获得优惠券折扣金额(以及使用优惠券类型的方法),这里是方法:
$order = wc_get_order( $order_id );
// GET THE ORDER COUPON ITEMS
$order_items = $order->get_items('coupon');
// print_r($order_items); // For testing
// LOOP THROUGH ORDER COUPON ITEMS
foreach( $order_items as $item_id => $item ){
// Retrieving the coupon ID reference
$coupon_post_obj = get_page_by_title( $item->get_name(), OBJECT, 'shop_coupon' );
$coupon_id = $coupon_post_obj->ID;
// Get an instance of WC_Coupon object (necessary to use WC_Coupon methods)
$coupon = new WC_Coupon($coupon_id);
## Filtering with your coupon custom types
if( $coupon->is_type( 'cash_back_fixed' ) || $coupon->is_type( 'cash_back_percentage' ) ){
// Get the Coupon discount amounts in the order
$order_discount_amount = wc_get_order_item_meta( $item_id, 'discount_amount', true );
$order_discount_tax_amount = wc_get_order_item_meta( $item_id, 'discount_amount_tax', true );
## Or get the coupon amount object
$coupons_amount = $coupons->get_amount();
}
}
因此,为了获得优惠券价格,我们使用WC_Coupon
get_amount()
方法